Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Dictionary to List with mixing of values and keys?

I have some dictionary. Let it be:

var dictionary = new Dictionary< string, List<MyClass>>();

I need to convert it to list of object that contains property from key and value. I did it with foreach loop in the next way:

var list = new List<dynamic>();
foreach (var key in dictionary.Keys)
{
    var values = dictionary[key];

    foreach (var obj in values)
    {
        list.Add(new
        {
            obj.Property0,
            obj.Property1,
            obj.Property2,
            ...
            key
        }
        );
    }
}

It works, but looks rudely as for me. Is it possible to do it more gracefully with LINQ?

like image 336
RredCat Avatar asked Feb 09 '23 14:02

RredCat


1 Answers

You can do that with a SelectMany.

var list = dictionary.SelectMany(
        kvp => kvp.Value, 
        (kvp,obj) => new {obj.Property0, obj.Property1, obj.Property2, kvp.Key})
    .ToList();

Or in query snytax

var list = (from kvp in dictionary
           from obj in kvp.Value
           select new {obj.Property0, obj.Property1, obj.Property2, kvp.Key})
    .ToList();

Note this results in a list of an anonymous class. If you really want dynamic you'll need to do a Cast<dynamic>() before the ToList(). Also if you want the last property of the anonymous class to be key instead of Key you'll need to do key = kvp.Key.

like image 121
juharr Avatar answered Feb 11 '23 03:02

juharr