Linq Cheat Sheet
Linq Cheat Sheet
Linq Cheat Sheet
Filtering
var col = from o in Orders where o.CustomerID == 84 select o;
Ordering
var col = from o in orders orderby o.Cost ascending select o; var col2 = orders.OrderBy(o => o.Cost);
var col9 = from o in orders orderby o.CustomerID, o.Cost descending select o; //returns same results as above var col5 = from o in orders orderby o.Cost descending orderby o.CustomerID select o; //NOTE the ordering of the orderbys
Joining
var col = from c in customers join o in orders on c.CustomerID equals o.CustomerID select new { c.CustomerID, c.Name, o.OrderID, o.Cost }; var col2 = customers.Join(orders, c => c.CustomerID,o => o.CustomerID, (c, o) => new { c.CustomerID, c.Name, o.OrderID, o.Cost } );
Grouping
var OrderCounts = from o in orders group o by o.CustomerID into g select new { CustomerID = g.Key, TotalOrders = g.Count() }; var OrderCounts1 = orders.GroupBy( o => o.CustomerID). Select(g => new { CustomerID = g.Key, TotalOrders = g.Count() });
NOTE:
the groupings key is the same type as the grouping value. E.g. in above example grouping key is an int because o.CustomerID is an int.
//skip first 2 and return the 2 after var col3 = (from o in orders where o.CustomerID == 84 orderby o.Cost select o).Skip(2).Take(2); var col3 = (from o in orders where o.CustomerID == 84 orderby o.Cost select o).Skip(2).Take(2);
//returns null if no elements var cust = (from c in customers where c.CustomerID == 84 select c).SingleOrDefault();
//returns a new customer instance if no elements var cust = (from c in customers where c.CustomerID == 85 select c).DefaultIfEmpty( new Customer()).Single(); //First, Last and ElementAt used in same way var cust4 = (from o in orders where o.CustomerID == 84 orderby o.Cost select o).Last(); //returns 0 if no elements var i = (from c in customers where c.CustomerID == 85 select c.CustomerID).SingleOrDefault();
NOTE:
Single, Last, First, ElementAt all throw exceptions if source sequence is empty. SingleOrDefault, LastOrDefault, FirstOrDefault, ElementAtOrDefault all return default(T) if source sequence is empty. i.e. NULL will be returned if T is a reference type or nullable value type; default(T) will be returned if T is a non-nullable value type (int, bool etc). This can be seen in the last example above.
ToDictionary
Dictionary<int, Customer> col = customers.ToDictionary(c => c.CustomerID); Dictionary<string, double> customerOrdersWithMaxCost = (from oc in (from o in orders join c in customers on o.CustomerID equals c.CustomerID select new { c.Name, o.Cost }) group oc by oc.Name into g select g).ToDictionary(g => g.Key, g => g.Max(oc => oc.Cost));
ToList
List<Order> ordersOver10 = (from o in orders where o.Cost > 10 orderby o.Cost).ToList();
ToLookup
ILookup<int, string> customerLookup = customers.ToLookup(c => c.CustomerID, c => c.Name);