简体   繁体   中英

C# - Convert Dictionary of Lists to List of Tuples with LINQ

I have a Dictionary:

Dictionary<int, List<(byte Id, string name)

The structure of this dictionary would be something like:

{
[1, {(1, "Leo"), (2, "Messi")}]
[2, {(3, "Cris"), (4, "Ronaldo")}]
}

How can i convert it into into the following using LINQ:

List<(int, byte)>

So the structure becomes something like:

{
(1,1),
(1,2),
(2,3),
(2,4),
}

TIA.

Assuming that your dictionary declared in the following way

var dict = new Dictionary<int, List<(byte Id, string name)>>
{
    {1, new List<(byte Id, string name)> {(1, "Leo"), (2, "Messi")}},
    {2, new List<(byte Id, string name)> {(3, "Cris"), (4, "Ronaldo") }}
};

You can convert it to List<(int, byte)> using SelectMany method

var list = dict.SelectMany(kvp => kvp.Value, (pair, tuple) => (pair.Key, tuple.Id)).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM