Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flat a IEnumerable by 2 Values?

Tags:

c#

.net

linq

class AgeClass
{
    string[] Names {get;set;}
    int Age {get;set;}
}

...

IEnumerable<AgeClass> myList = ...; // a few instances of AgeClass

now i want to get (out of myList) a

IEnumerable<KeyValuePair<string,int>> 

with a Pair of Name and Age. How to do this easily?

like image 539
Sheldon Cooper Avatar asked Dec 21 '25 11:12

Sheldon Cooper


1 Answers

myList.SelectMany(
     x=> x.Names.Select(
          z => new KeyValuePair<string,int>(z,x.Age)));

Note that you must be aware that linq is creating a query - each time you enumerate this collection new one will be created based on current state of myList. To remove this effect simply add .ToList() to the end of this line.

like image 150
Rafal Avatar answered Dec 23 '25 01:12

Rafal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!