Search code examples
c#linqlambdaunique

Select distinct list from nested collections on multiple fields


I am trying to get distinct list of nested object from collection using LINQ.

Please check the below scenario

I have list of ClientAccounts,in every client account there is list of Holdings and in each holding has Instrument Type. I am trying to get unique instrument list from list of client accounts.

So far I have tried with below query, but it returns all the instruments. clientAcccounts is list of Client Account.

List<Instrument> lstclientInstrument = clientAcccounts
                                          .SelectMany(x => x.Holdings)
                                          .Select(s => new Instrument { 
                                                          InstrumentID = s.Instrument.InstrumentID, 
                                                          AssetTypeID = s.Instrument.AssetTypeID 
                                                       })
                                          .Distinct()
                                          .ToList();

Any suggestion to get distinct list.


Solution

  • Try This Group by with multiple Keys.

    List<Instrument> ins = clientAcccounts.SelectMany(x => x.Holdings.Select(s => s.Instrument)).ToList().GroupBy(p=> new {p.InstrumentID,p.AssetTypeID},(key,group)=>group.First()).ToList<Instrument>();