C# GroupBy并计算列表中的唯一元素
我有一个只包含字符串的列表。我想做的是分组并返回计数 例如:C# GroupBy并计算列表中的唯一元素,c#,.net,C#,.net,我有一个只包含字符串的列表。我想做的是分组并返回计数 例如: Foo1 Foo2 Foo3 Foo1 Foo2 Foo2 将导致Foo1:2、Foo2:3、Foo3:1。我试过使用Linq,但列表中有一个GroupBy,可能会起作用,但我把它搞砸了,无法理解它的用途:(var list=new list{“Foo1”、“Foo2”、“Foo3”、“Foo2”、“Foo3”、“Foo1”、“Foo1”}; var=list .GroupBy(s=>s) .Select(group=>new{W
Foo1
Foo2
Foo3
Foo1
Foo2
Foo2
将导致Foo1:2、Foo2:3、Foo3:1。我试过使用Linq,但列表中有一个GroupBy,可能会起作用,但我把它搞砸了,无法理解它的用途:(var list=new list{“Foo1”、“Foo2”、“Foo3”、“Foo2”、“Foo3”、“Foo1”、“Foo1”};
var=list
.GroupBy(s=>s)
.Select(group=>new{Word=group.Key,Count=group.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>");
}
NWindCustomersDataContext dc=new NWindCustomersDataContext();
var query=(来自dc.Customers中的c)
在dc中加入o。c.CustomerID上的订单等于o.CustomerID
o组由c.CustomerID转换为g组
选择新的
{
CustomerID=g.键,
公司=(来自dc客户)
其中cust.CustomerID==g.Key
选择cust).ToList(),
Count=g.Select(x=>x.OrderID).Distinct().Count()
}).OrderByDescending(y=>y.Count);
foreach(查询中的var项)
{
响应。写入(“CustomerID:+item.CustomerID+”“+”公司名称:“+item.Company[0]。公司名称。ToString()+””;
}
您可以找到一个非常好的示例上有一个很好的解决方案 它按键对数据进行分组;每个键都有自己的数据列表,您可以对其进行迭代
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>");
}