代码之家  ›  专栏  ›  技术社区  ›  sp_m

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

  •  1
  • sp_m  · 技术社区  · 8 年前

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

    请检查以下场景

    我有 客户帐户 ,在每个客户帐户中都有 控股公司 在每个控股中 仪器 类型我正在尝试从客户帐户列表中获取唯一的工具列表。

    到目前为止,我尝试了下面的查询,但它返回了所有的工具。ClientAccounts是客户端帐户的列表。

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

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

    1 回复  |  直到 8 年前
        1
  •  4
  •   vinit jain    8 年前

    使用多个键尝试此分组方式。

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