// Query Syntax var col1 = from o in Orders selectnew { OrderID = o.OrderID, Cost = o.Cost }
// Lambda Syntax var col2 = Orders.Select(o => new { OrderID = o.OrderID, Cost = o.Cost });
Ording 排序
1 2 3 4 5 6 7
// Query Syntax var col1 = from o in Orders orderby o.Cost ascending select o;
// Lambda Syntax var col2 = Orders.OrderBy(o => o.Cost);
1 2 3 4 5 6 7
// Query Syntax var col1 = from o in Orders orderby o.Cost descending select o;
// Lambda Syntax var col2 = Orders.OrderByDescending(o => o.Cost);
1 2 3 4 5 6 7 8 9 10 11 12
// Query Syntax var col1 = from o in Orders orderby o.CustomerID, o.Cost descending select o; var col2 = from o in Orders orderby o.Cost descending orderby o.CustomerID select o;
// Query Syntax var col1 = from c in Customers join o in Orders on c.CustomerID equals o.CustomerID selectnew { c.CustomerID, c.Name, o.OrderID, o.Cost };
// Lambda Syntax var col2 = Customers.Join(Orders, c => c.CustomerID, o => CustomerID, (c, o) => new { c.CustomerID, c.Name, o.OrderID, o.Cost });
Grouping 群組
使用 Grouping 時,其 Key 的型別會和 Value 一樣,例如 o.CustomerID 型別是 int 則其 Key 也是 int型別。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Query Syntax var OrderCounts1 = from o in Orders group o by o.CustomerID into g selectnew { CustomerID = g.Key, TotalOrders = g.Count() };
// Lambda Syntax var OrderCounts2 = Orders.GroupBy(o => o.CustomerID) .Select(g => new { CustomerID = g.Key, TotalOrders = g.Count() });
Paging 分頁
分頁基本上就是 Skip 和 Take 的應用。
1 2 3 4 5 6 7 8 9
// select top 3 // Query Syntax var col1 = (from o in Orders where o.CustomerID == 23 select o).Take(3);
// returns a new customer instance if no elements // Query Syntax var cust1 = (from c in Customers where c.CustomerID == 21 select c) .DefaultIfEmpty(new Customer()).Single();
// To Array string[] names = (from c in Customers select c.Name).ToArray();
// To Dictionary 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 selectnew { 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();