Get results of group by and add to multiple lists c#

Viewed 70

I have a list that has been De-serialized from an XML file in to.

XmlRootAttribute Root = new XmlRootAttribute();
Root.ElementName = "PersonList";

List<Person> persons;
using (var reader = new StreamReader("Test.xml"))
{
    XmlSerializer deserializer = new 
    XmlSerializer(typeof(List<Person>),Root);
    persons = (List<Person>)deserializer.Deserialize(reader);
}

My XML file

   <PersonList>
      <Person xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <ID>4</ID>
          <Name>dasdas</Name>
          <Address>asdasd</Address>
          <Number>40</Number>
       </Person>
   </PersonList>

I want to group by each ID, so get all of the results if ID = '4' then add that to a PersonsID4 List or if ID = '5' add to PersonsID5 List

var test = persons.GroupBy(u => u.ID).Select(p => p.ToList()).ToList();
personslist4 = test;

If question has been asked, please direct.

2 Answers

A common thing to do after GroupBy is to construct a Dictionary that maps IDs to lists of items:

var test = persons
    .GroupBy(u => u.ID)
    .ToDictionary(g => g.Key, g => g.ToList());

This lets you pick a list of users with a specific ID, and to iterate all IDs with their corresponding user lists:

foreach (var p in test) {
    var id = p.Key;
    var list = p.Value;
    Console.WriteLine("ID={0}: {1} persons", id, list.Count);
}

If you are not comfortable with linq group by

// declare the dictionary

  static Dictionary<int, List<Person>> dictionaryPerson = new Dictionary<int, List<Person>>();

// if dictionary has already the key then add the list else create a new entry in dictionary

foreach (var person in persons)
                {
                    if (!dictionaryPerson.ContainsKey(person.Id))
                    {
                        dictionaryPerson.Add(person.Id, new List<Person> { person });
                    }
                    else
                    {
                        dictionaryPerson[person.Id].Add(person);
                    }
                }
Related