public class ClassA { public string MyString {get; set;} } public class ClassB { public List<ClassA> MyObjects {get; set;} } List<ClassB> classBList = new List<ClassB>(); var results = (from i in classBList select i.MyObjects).Distinct();
I want a distinct list of all the ClassA
objects in the classBList
. How do I go about this using LINQ? I'm thinking about a nested query, but couldn't quite figure it out. Any help is very appreciated.
The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>.
The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.
SelectMany(<selector>) method For example, SelectMany() can turn a two-dimensional array into a single sequence of values, as shown in this example: int[][] arrays = { new[] {1, 2, 3}, new[] {4}, new[] {5, 6, 7, 8}, new[] {12, 14} }; // Will return { 1, 2, 3, 4, 5, 6, 7, 8, 12, 14 } IEnumerable<int> result = arrays.
You're trying to select multiple result objects for each ClassB
object in the original list.
Therefore, you're looking for the SelectMany
extension method:
var results = classBList.SelectMany(b => b.MyObjects).Distinct();
If you want to use query expressions, you'll need to use two from
clauses:
var results = (from b in classBList from a in b.MyObjects select a).Distinct();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With