1

I have a List<KeyValuePair<string, Records> mylist;

I would like to loop in the list foreach different key value. Something like

foreach(var item in myList.select(/\*query the disctinct values of key here ?*/)

is it possible ? How ?

Ythio Csi
  • 379
  • 2
  • 14
  • 1
    You can probably get a good footing by looking [here](http://stackoverflow.com/questions/998066/linq-distinct-values), for starters.. – gravity Apr 26 '17 at 15:37
  • I'll check it, thanks – Ythio Csi Apr 26 '17 at 15:44
  • 1
    If you have a list of pairs that has duplicate keys, how will you determine which value to use for a key that has multiple values tied to it? Ex: `key: 1, value: "hello"`; `key: 1, value: "world"`. How do you pick between "hello" and "world" since they have the same key? – Blake Thingstad Apr 26 '17 at 15:48
  • I may have poorly explain my needs. I will reuse your comment exemple to help me. I need something like serialize/display/process together all elements with key = 1, then serialize/display/process together all element with key = 2, etc... – Ythio Csi Apr 27 '17 at 08:47

1 Answers1

4

You can do

foreach(var item in myList.Select(x => x.Key).Distinct())
{
    //Your Logic
}

myList.Select(x => x.Key).Distinct() would give you distinct Keys and foreach will loop over them.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208