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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With