简体   繁体   English

检查列表中的每个项目是否属于某个组并创建一个新列表

[英]Check if each item in a list belongs to certain group and create a new list

I have a list of stored ids. 我有一个存储的ID列表。 I need to group these id into a separate group of list based on if each id belongs to certain group. 我需要根据每个ID是否属于某个组将这些ID分组到一个单独的列表组中。 For instance in below example, I would like to return: 例如在下面的示例中,我想返回:

List<Group1> = {1,2};
List<Group2> = {3,4};
List<Group3> = {5};

Now I have hundreds of group, so i can't literally create a group and add items to that group. 现在我有数百个群组,因此我无法从字面上创建一个群组并将项目添加到该群组中。 So, how can I create and return these groups dynamically? 因此,如何动态创建和返回这些组?

List<int> list = new List<int> { 1, 2, 3, 4, 5 };   
foreach (int i in list)
{
 var x = PersonList.GetById(I); //Returns Person object
 var obj = x.GroupBy(y => y.GroupName).ToList();
// where obj is IEnumerable<IGrouping<string,Person>>
// I can get Group1 from Person object
//how to get List<Group2> ...and so on?
}

You need to do this 你需要这样做

var obj = x.GroupBy(y => y.GroupName); // IEnumerable<IGrouping<string,Person>>

Now in order to get list that belongs to certain group you need to check the IGrouping's key with your own key (that you used to make grouping). 现在,为了获取属于特定组的列表,您需要使用自己的密钥(用于分组)检查IGrouping的密钥。

var group2 = obj.Where(g => g.Key == "Group2").SelectMany(g => g).ToList();

如果只希望将人员分组,则下面的查询会将其放入词典中,词典的关键字将是组名,值将是Person对象的列表。

var groups = obj.ToDictionary( t => t.Key, t => t);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM