Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq - select distinct values

Tags:

linq

distinct

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?

like image 652
Bick Avatar asked Sep 12 '13 07:09

Bick


1 Answers

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
);
like image 195
Giannis Paraskevopoulos Avatar answered Oct 01 '22 03:10

Giannis Paraskevopoulos