Linq - select distinct values

18,874
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
);
Share:
18,874
Bick
Author by

Bick

Updated on July 25, 2022

Comments

  • Bick
    Bick almost 2 years

    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?

  • Bick
    Bick over 10 years
    Thanks for the quick answer. Improved my question by adding more fields (not to be used in the distinct)
  • cuongle
    cuongle over 10 years
    What if there are some duplicate vendor after distinct, it would break dictionary
  • Giannis Paraskevopoulos
    Giannis Paraskevopoulos over 10 years
    @CuongLe Then there must be more info on what to do with unit. We could change it to GroupBy, but then we would need to know how to handle units. But until otherwise noted the solution stands.