Sturm
Sturm

Reputation: 4125

Create a Dictionary from a list with duplicates

My scenario is that I have a List<MyObject> and MyObject has a property ID. I want to make a dictionary from that list:

        var myDic = MyList.ToDictionary(e => e.ID);

The problem is that sometimes I have some duplicate ID. In that case I would like to store the first item to the dictionary and ignore the rest, and have some kind of notification of skipped items if possible.

Right now I'm obtaining an Exception telling me that I have duplicate keys in my list but I can't/don't want to modify the original list. Is there a way of performing the task without creating a new list with no duplicate IDs?

Upvotes: 1

Views: 1855

Answers (2)

EZI
EZI

Reputation: 15354

var myDic = MyList.ToLookup(x => x.ID)
                  .ToDictionary(x => x.Key, x => x.First());

Upvotes: 9

Servy
Servy

Reputation: 203821

Just group the items by that property first, then you can pull out the first/last/random/whatever value you want from that group.

var dictionary = list.GroupBy(item => item.ID)
    .ToDictionary(group => group.Key, group => group.First());

Upvotes: 6

Related Questions