Skip to main content
 首页 » 编程设计

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

2024年02月04日27unruledboy

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

请检查以下场景

我有 ClientAccounts 列表,在每个客户帐户中都有 Holdings 列表,并且在每个 holding 中都有Instrument 类型。我正在尝试从客户账户列表中获取唯一的工具列表。

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

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

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

请您参考如下方法:

尝试使用多个键进行分组。

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