score:14

Accepted answer
    var qry = headers.groupby(row => row.destinationlocation)
        .todictionary(grp => grp.key, grp => grp.first());

or (equivalent):

    var dictionary = (from row  in headers
              group row by row.destinationlocation)
              .todictionary(grp => grp.key, grp => grp.first());

i wonder, though, if your current foreach code isn't already better - it doesn't buffer the ones it intends to drop, for example.

score:2

var headerlocationlookup = populateheaders()
    .aggregate(new dictionary<string, iheaderrecord>(), (header, d) => {
        if(d.containskey(header.destinationlocation)) 
            d[header.destinationlocation] = header;

        return d;
    });

i don't think this is any clearer than the existing code though.

score:5

i wrote a blog post a while back that shows you how you can create overloads of distinct that use a lambda expression as the key selector instead of a custom comparer, which would let you write:

headers.distinct(h => h.destinationlocation)
       .todictionary(h => h.destinationlocation);

it does use a custom comparer underneath, but the extension method constructs that stuff for you, and makes it much easier to read.


Related Query

More Query from same tag