15

I want to use LINQ to select a unique list of strings, stored as a List, inside an object. This object is itself stored in a List inside another object. It's hard to explain, here is an example:

public class Master { public List<DataCollection> DateCollection { get; set; } public Master() { this.DateCollection = new List<DataCollection>(); } } public class DataCollection { public List<Data> Data { get; set; } public DataCollection() { this.Data = new List<Data>(); } } public class Data { public string Value{ get; set; } public Data() { } } 

Using the Master class, I want to get a list of unique Value strings in the Data class. I have tried the following:

List<string> unique = master.Select(x => x.DataCollection.Select(y => y.Value)).Distinct().ToList(); 

Can somebody show me how it's done?

2
  • So you want the distinct Data of all your DataCollection's data stapled together? Commented Apr 16, 2015 at 15:52
  • make distinct go in inner parantheses such as master.select(x=>x.DataCollection.Select(y=>y.value).Distinct()) . Your metohd right now gets distinct master not distinct inner values Commented Apr 16, 2015 at 15:52

2 Answers 2

31

You can do that like this, directly using the public DateCollection member:

var unique = master.DateCollection .SelectMany(x => x.Data.Select(d => d.Value)) .Distinct() .ToList(); 

The key being SelectMany to "flatten" the selection.

Sign up to request clarification or add additional context in comments.

Comments

11

SelectMany projects a list of lists into a single list:

List<string> unique = master .SelectMany(x => x.DataCollection.Select(y => y.Value)) .Distinct() .ToList(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.