Bick
Bick

Reputation: 18551

Linq - select distinct values

I have the following object in a collection (List)

public class MyObject{

    string vendor;
    string unit;

    int unit123;
    AnotherObject unit456;
}

This can be long and repetitive.

I want to select, using linq, only the distinct values of vendor and unit and put it in the following structure

Dictionary

Is it possible?

Upvotes: 9

Views: 18883

Answers (1)

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

List<MyObject> l = new List<MyObject>();
//fill the list

Dictioonary<string,string> d = 
l
.Select
(
    x=>new
    {
        x.vendor,
        x.unit
    }
) //Get only the properties you care about.
.Distinct()
.ToDictionary
(
    x=>x.vendor,  //Key selector
    x=>x.unit     //Value selector
);

Upvotes: 11

Related Questions