我有一个只包含字符串的列表。我想做的是分组并返回计数。
例如:
Foo1
Foo2
Foo3
Foo1
Foo2
Foo2
会导致 Foo1: 2, Foo2: 3, Foo3: 1。我尝试过使用 Linq,但列表中有一个 GroupBy 可能会解决问题,但我搞砸了,不知道用途:(
var list = new List<string> { "Foo1", "Foo2", "Foo3", "Foo2", "Foo3", "Foo3", "Foo1", "Foo1" };
var grouped = list
.GroupBy(s => s)
.Select(group => new { Word = group.Key, Count = group.Count() });
var items= myList
.GroupBy(g => g)
.Select(t => new {count= t.Count(), key= t.Key });
foreach (var group in items)
Console.WriteLine ( group.key + " " + group.count);
var grouped = select new
{
Foo= grp.Key,
Bar= grp.Select(x => x.SomeField).Distinct().Count()
};
NorthWind 数据库的工作示例,以便您检查::
NWindCustomersDataContext dc = new NWindCustomersDataContext();
var query = (from c in dc.Customers
join o in dc.Orders on c.CustomerID equals o.CustomerID
group o by c.CustomerID into g
select new
{
CustomerID = g.Key,
Company = (from cust in dc.Customers
where cust.CustomerID == g.Key
select cust).ToList(),
Count = g.Select(x => x.OrderID).Distinct().Count()
}).OrderByDescending(y => y.Count);
foreach (var item in query)
{
Response.Write("CustomerID: " + item.CustomerID + "</br>" + "CompanyName: " + item.Company[0].CompanyName.ToString() + "</br>");
}
在这里你可以找到一个很好的例子
http://msdn.microsoft.com/en-us/library/vstudio/bb534304(v=vs.100).aspx提供了一个很好的解决方案 。每个键都有自己的数据列表,您可以对其进行迭代。