获取不同项目及其数量的列表 [英] Get a list of distinct items and their count

查看:86
本文介绍了获取不同项目及其数量的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它具有许多属性,但唯一需要担心的两个是:

I have an object, that has many properties but the only two to worry about are:

myobject.IDint
myobject.NamesHashSet

myobject.ID which is an int
myobject.Names which is a HashSet

然后,我有一个类似于以下内容的对象List:

Then I have a List of those objects that looks something similar to this:

List<myobject>

我使用Linq将一些数据放入中继器,但是我不确定如何获取名称列表以及它们出现的频率.

I use Linq to get a some of the data into a repeater, but I'm not sure how to get the list of Names and how often they show up.

想使用Linq来避免遍历数据.

Want to use Linq to avoid having to loop through the data.

正如我的标签所示,这是一个使用C#的ASP.NET解决方案.

As my tags should show, this is an ASP.NET solution using C#.

一些说明:
可以说我的清单中只有三个项目: 第1项的名称中包含John,Fred,Jack. 第2项的名称中包含John,Fred,Joe. 第3项的名称为John.

Some clarification:
Lets say I have just three items in my list: Item 1 has John, Fred, Jack in its names. Item 2 has John, Fred, Joe in its names. Item 3 has John in its names.

我正在尝试返回以下内容: 约翰-3 弗雷德-2 杰克-1 乔-1

I am trying to return the following: John - 3 Fred - 2 Jack - 1 Joe - 1

此外,作为注释,我熟悉必须为对象编写自己的比较器,但我只是想念总体解决方案的方法".

Also, as a note I am familiar with having to write my own comparer for my object, I'm just missing the 'how to' for the overall solution in my thoughts.

推荐答案

这是我如何理解您要解决的问题.您有一个myobject的列表.每个myobject都有一个名为Names的属性,该属性是string s(即HashSet<string>)的HashSet.您要计算出现在某些myobject.Names中的每个string在所有myobject.Names中出现的次数.也就是说,你有

Here is how I understand the problem that you are trying to solve. You have a list of myobjects. Each myobject has a property called Names which is a HashSet of strings (i.e., HashSet<string>). You want to count the number of times each string that appears in some myobject.Names appears in all the myobject.Names. That is, you have

"Alice", "Bob", "Charlie"
"Alice", "Bob", "Donald"
"Alice", "Donald", "Ernie"

作为三个myobject.Names,您想看

"Alice", 3
"Bob", 2
"Charlie", 1
"Donald", 2
"Ernie", 1

如果是这样:

var query = list.SelectMany(x => x.Names)
                .GroupBy(s => s)
                .Select(g => new { Name = g.Key, Count = g.Count() });

foreach(var result in query) {
    Console.WriteLine("Name: {0}, Count: {1}", result.Name, result.Count);
}

我看不到myobject.ID在这里扮演什么角色.请符合条件.

I do not see what role myobject.ID plays here. Please qualify.

这篇关于获取不同项目及其数量的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆