LINQ in C#
Query any data source with SQL-like syntax. Filter, transform, aggregate.
60-Second Version: LINQ = Language Integrated Query. Filter and shape data like SQL but in C#. Think of Kunal sorting pizza orders.
1. Why LINQ? Stop Writing Foreach Hell
Kunal has 1000 pizza orders. He wants veg pizzas over โน500. Without LINQ: create list, foreach, if checks, add to result. With LINQ: one line.
var expensiveVeg = orders.Where(o => o.IsVeg && o.Price > 500).ToList();
2. Two Flavors: Method vs Query Syntax
// Method syntax
var names = orders.Where(o => o.IsVeg).Select(o => o.CustomerName);
// Query syntax - compiles to same thing
var names = from o in orders
where o.IsVeg
select o.CustomerName;
Pick one. Industry uses Method syntax 90% of the time.
3. Deferred Execution: The Big Idea
LINQ doesn't run until you enumerate. Prerna builds a query but doesn't call ToList(). No DB hit yet. Only when Kaushal does foreach or ToList() does it execute once.
var query = orders.Where(o => o.IsVeg); // Nothing runs
var result = query.ToList(); // NOW it runs
Beginner Trap: Sanju writes
if(query.Any()) { var list = query.ToList(); }. That's two DB calls. Fix: var list = query.ToList(); if(list.Any()). One hit.
No comments yet. Be the first to share your thoughts!