从多个字段的嵌套集合中选择不同的列表

时间:2018-05-05 11:38:15

标签: c# linq lambda unique

我正在尝试使用LINQ从集合中获取不同的嵌套对象列表。

请检查以下方案

我有 ClientAccounts 列表,在每个客户帐户中都有馆藏列表,每个持有工具类型。我正试图从客户帐户列表中获取唯一的工具列表。

到目前为止,我已尝试使用以下查询,但它会返回所有乐器。 clientAcccounts是客户帐户列表。

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

任何有关获得不同列表的建议。

1 个答案:

答案 0 :(得分:3)

使用多个密钥尝试此组。

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>();
相关问题