9

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?

1
  • Can you explain the Key and Value of your dictionary? Commented Sep 12, 2013 at 7:52

1 Answer 1

11
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 ); 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the quick answer. Improved my question by adding more fields (not to be used in the distinct)
What if there are some duplicate vendor after distinct, it would break dictionary
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.