Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
XML
<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:
XML
<Animal id="2">
 <AnimalTeam>
   <AnimalTeamCode>RTB1</AnimalTeamCode>
   <AnimalTeamCode>RTB2</AnimalTeamCode>
 <AnimalTeam>
<animal>


What I have tried:

currently this how i am using the GroupBy operator
C#
//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?
Posted
Updated 28-Nov-16 11:11am
v6
Comments
#realJSOP 28-Nov-16 13:55pm    
How are you able to generate that output. It's malformed XML. Further, your variable names quite frankly suck since we don't know what "a" is a type of, nor the properties within it, nor why you're using a dictionary.
Eagle32 28-Nov-16 14:21pm    
My XML is not being correctly parsed when i pasted it into the post. How can i fix this?
#realJSOP 28-Nov-16 14:24pm    
When you paste it, paste it as a code block, and it should determine the correct language automatically. If it doesn't, make sure the "lang" element is set to "XML".

1 solution

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:

C#
var groupedCollection = listOfAnimals.GroupBy(animal => animal.ID)
                                     .ToDictionary( group => group.Key, 
                                                    group => group.ToList()
                                                   );
 
Share this answer
 
Comments
Eagle32 28-Nov-16 16:53pm    
Ok thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900