使用groupby对复杂集合进行分组 [英] Grouping a complex collection using groupby

查看:332
本文介绍了使用groupby对复杂集合进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在查询中处理以下结果集。查询结果是动物的集合。每个Animal都可以分配给多个团队。

查询结果

ID TYPE TEAMCODE

2 MAMMAL RTB1

2 MAMMAL RTB2



我可以产生以下输出,但它只是包括第一个AnimalTeamCode RTB1

I am dealing with the following result set in my query. The query result is a collection of Animals. Each Animal can be allocated to more than one team.
Query Result
ID TYPE TEAMCODE
2 MAMMAL RTB1
2 MAMMAL RTB2

I can produce the following output but it only includes the first AnimalTeamCode RTB1

<Animal id="2">
 <AnimalTeam>
   <AnimalTeamCode>RTB1</AnimalTeamCode>
 <AnimalTeam>
<animal>







我想要实现的是每只动物,如果是分配给多个团队我希望像这样显示:




What i am trying to achieve is that for each Animal, if its been allocated to more than one team i want to show it like this:

<Animal id="2">
 <AnimalTeam>
   <AnimalTeamCode>RTB1</AnimalTeamCode>
   <AnimalTeamCode>RTB2</AnimalTeamCode>
 <AnimalTeam>
<animal>





我尝试过:



目前这是我如何使用GroupBy运算符



What I have tried:

currently this how i am using the GroupBy operator

//code to get the listOfAnimals
 ......
 //Group the list of Animals
var groupedCollection = listOfAnimals.GroupBy(animal => animal.ID).ToDictionary(animal => animal.key, animal => animal.Value.ToList())





我如何对结果进行分组以便我可以实现上述目标?



How can i group the results so i can achieve the above?

推荐答案

您没有正确执行此操作,您需要在使用ToDictionary时设置Key和Value属性,只需将ToDictionary调用更改为:



You are not doing it correctly, you need to set the Key and Value property while using ToDictionary, just change the ToDictionary call to be like:

var groupedCollection = listOfAnimals.GroupBy(animal => animal.ID)
                                     .ToDictionary( group => group.Key, 
                                                    group => group.ToList()
                                                   );


这篇关于使用groupby对复杂集合进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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