How to convert a dictionary to a list with a mix of values ​​and keys?

I have a dictionary. Let it:

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

I need to convert it to a list of objects containing a property from a key and a value. I did this with a foreach loop as follows:

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 it looks rude for me. Is it possible to do this more elegantly with LINQ?

+4
source share
1 answer

You can do this with SelectMany.

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

Or in snytax request

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

, . dynamic, Cast<dynamic>() ToList(). , , key key, key = kvp.Key.

+8

Source: https://habr.com/ru/post/1615578/