Linq 用法笔记
Linq中怎么用 between…and?
var query = from p in context.Parent from c in context.Child.Where(x => p.cob >= x.effective) .Where(x => p.cob <= x.expiry) .DefaultIfEmpty() group p by p.cob into pg select new { cob = pg.Key, count = pg.Count() };
下面这个是用多个where条件来处理between…and,但是是内连接。
var appointmentNoShow = from a in appointments from p in properties from c in clients where a.Id == p.OID where a.Start.Date >= startDate.Date where a.Start.Date<=endDate.Date
怎么用 in ?
var allowedStatus = new[]{ "A", "B", "C" }; var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));
or in query syntax: var filteredOrders = from order in orders.Order where allowedStatus.Contains(order.StatusCode) select order;
怎么使用多个连接条件 join...on ?
var query = from obj_i in set1 join obj_j in set2 on new { JoinProperty1 = obj_i.SomeField1, JoinProperty2 = obj_i.SomeField2, JoinProperty3 = obj_i.SomeField3, JoinProperty4 = obj_i.SomeField4 } equals new { JoinProperty1 = obj_j.SomeOtherField1, JoinProperty2 = obj_j.SomeOtherField2, JoinProperty3 = obj_j.SomeOtherField3, JoinProperty4 = obj_j.SomeOtherField4 }
http://stackoverflow.com/questions/3020442/linq-joining-in-c-sharp-with-multiple-conditions
如果要达到这个sql的效果:
SELECT * FROM table1 a LEFT JOIN table2 b ON a.col1 = b.key1 AND a.col2 = b.key2 AND b.from_date <= now() AND b.deleted = 0;
可以这样:
var query = (from x in context.table1 join y in context.table2 on new { Key1 = x.col1, Key2 = x.col2 Key3 = true, Key4 = true } equals { Key1 = b.key1, Key2 = b.key2, Key3 = b.from_date< DateTime.Now, Key4 = !b.deleted } into result from r in result.DefaultIfEmpty() select new {x.Something, r.Something}
http://stackoverflow.com/questions/7765230/linq-to-entity-multiple-join-conditions
怎么使用group ... by 分组?
如sql:
SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>
group x by new { x.Column1, x.Column2 } 或者: .GroupBy(x => new { x.Column1, x.Column2 })
var query = (from t in Transactions group t by new {t.MaterialID, t.ProductID} into grp select new { grp.Key.MaterialID, grp.Key.ProductID, Quantity = grp.Sum(t => t.Quantity) }).ToList();