Home > database >  List of objects to List of Lists in C#
List of objects to List of Lists in C#

Time:05-15

I have a List of objects, say List<MyObject> = new List<MyObject>{object1, object2, ..., object10}

Each object has property "Property1" which is a dictionary with different number of keys for each object, where for each key, the value is again a dictionary but here the value for each key is a string. I would like to convert this List<object> to List<List<string>>, so for each object I want to create a list with string values, where values are taken from this nested dictionary.

CodePudding user response:

The fast way to map it again:

var newList = new List<List<string>>();
    foreach(var item in items){
        newList.Add(item.Property1.Values.ToList<string>());
    }

CodePudding user response:

I think it's this:

yourList.Select(mo => mo.Property1.SelectMany(d => d.Value.Values).ToList()).ToList();

It produces a List<List<string>> - i'll use bold and italic to distinguish:

  • yourList.Select produces the enuemration that will become the List, so there is one entry in the List for every entry in the list of MyObject
  • mo.Property1.SelectMany enumerates the outer dictionary of Property1, getting the Value.Values for each entry in the outer dictionary.
    • Each outer entry's Value is the inner Dictionary<...,string> and hence is a Dictionary with a Values collection that is a bunch of strings. Value.Values thus represents a collection of strings associated with each outer dictionary entry
    • Fed with these multiple "collection of strings" SelectMany collapses them into a single enumeration of strings, that is converted the a list with ToList, thus the .ToList() on SelectMany() gives you the List
  • The .ToList() at the end of the expression gives you the List< ... >
  •  Tags:  
  • c#
  • Related