sp_m
sp_m

Reputation: 2707

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.

Upvotes: 1

Views: 1284

Answers (1)

vinit jain
vinit jain

Reputation: 252

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>();

Upvotes: 4

Related Questions