摘要:LINQ練習
練習了一下LINQ的寫法,以前總是要使用迴圈處理的一些動作,都變成LINQ的語法,程式變簡單好多,
LINQ還真是讓人愛不釋手的好東西。
Count的作法
var count = (from item in doc.Root.Element("channel").Elements("item")
where DateTime.Parse(item.Element("pubDate").Value) >= new DateTime(2009, 2, 1)
select item).Count();
Console.WriteLine(count);
Group by的作法
var collection = from item in doc.Root.Element("channel").Elements("item")
group item by DateTime.Parse(item.Element("pubDate").Value).ToString("yyyy/MM") into g
select new { Date = g.Key, Count = g.Count() };
Join的作法
var orders = from order in dataSet.Orders
group order by order.CustomerID into g
join customer in dataSet.Customers on g.Key equals customer.CustomerID
select new
{
CustomerID = customer.CustomerID,
Company = customer.CompanyName,
OrdersCount = g.Count()
};
Distinct的作法
var orderDistinct = (from order in dataSet.Orders select order.CustomerID).Distinct();