Concatenate collection from property

class oA {    int type;    List<oB> list; }  class oB {    int id,    decimal price,    string name } 

somewhere you get a list from oA objects.

What is the correct way to have 1 list of oB objects from all the oA objects of a certain type?

i was thinking something like this

var myoAs = new List<oA>(); /* Load data from wherever */ var myList =  myoAs.Where(x => x.type == 1).select(....) 

Who knows the anwer how to get a complete list of all the oB objects (and even remove duplicates in the linq as well if possible)

Add Comment
2 Answer(s)

Use SelectMany to aggregate multiple lists and Distinct to filter duplicates.

var myList =  myoAs.Where(x => x.type == 1).SelectMany(a => a.list).Distinct(); 
Add Comment

You can use this extension method

IEnumerable distinctList = myoAs.SelectMany(x=>x.list).DistinctBy(x => x.name);

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(     this IEnumerable<TSource> source,     Func<TSource, TKey> keySelector) {     var knownKeys = new HashSet<TKey>();     return source.Where(element => knownKeys.Add(keySelector(element))); } 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.