分组依据 并计算列表中的唯一元素
本文关键字:唯一 元素 列表 计算 | 更新日期: 2023-09-27 18:35:55
我有一个只包含字符串的列表。我想做的是分组并返回一个计数。
例如:
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()
};
罗斯文数据库的工作示例,以便您可以检查::
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它按键对数据进行分组;每个键都有自己的数据列表,您可以对其进行迭代。