1

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.

rene
  • 41,474
  • 78
  • 114
  • 152
sp_m
  • 2,647
  • 8
  • 38
  • 62
  • 2
    Instead of using Distinct use .GroupBy(x => x.InstrumentID).Select(x => x.FirstOrDefault()).ToList(); – jdweng May 05 '18 at 11:52
  • Possible duplicate: https://stackoverflow.com/questions/8560884/how-to-implement-iequalitycomparer-to-return-distinct-values – mshwf May 05 '18 at 12:10

1 Answers1

4

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>();
vinit jain
  • 222
  • 2
  • 3