LINQ-合并多个列表以形成一个新列表并按键对齐它们吗? [英] LINQ - Combine multiple lists to form a new list and align them by key?

查看:75
本文介绍了LINQ-合并多个列表以形成一个新列表并按键对齐它们吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同列的列表,但是每个列表都有一个具有相同键的公共列,如何将它们组合成一个新列表,即:

I have two list of different columns, but each list have a common column with the same key, how do I combine them into a new list, i.e:

public class TradeBalanceBreak
{
    public int CommID { get; set; }
    public int CPFirmID { get; set; }
    public double CreditDfferenceNotional { get; set; }
    public string Currency { get; set; }
}

public class Commission
{
    public int CommID { get; set; }
    public PeriodStart { get; set; }
    public ResearchCredit { get; set; }
}

public class CommissionList
{
    public List<Commission> Commissions { get { return GetCommissions(); }}

    private List<Commission> GetCommissions()
    {
        // retrieve data code ... ...
    }
}

public class TradeBalanceBreakModel
{
    public List<TradeBalanceBreak> TradeBalanceBreaks { get; set; }
}

public class CommissionModel
{
    public List<CommissionList> CommissionLists { get; set; }
}

我想实现的是将TradeBalancesBreaksCommissionLists(来自模型类)组合/展平. CommID在两者之间共享.

What I would like to achieve is to combine/flatten the TradeBalancesBreaks and CommissionLists (from the model classes) into one. The CommID is shared between the two.

谢谢.

推荐答案

使用Join(扩展方法版本)-更新后

Using Join (extension method version) -- after your update

 var list1 = GetTradeBalanceBreaks();
 var list2 = new CommisionsList().Commissions;

 var combined = list1.Join( list2,  l1 => l1.ID, l2 => l2.First().ID,
                            (l1,l2) = > new
                                        {
                                           l1.CommID, 
                                           l1.CPFirmID,
                                           l1.CreditDifferenceNotional,
                                           l1.Currency,
                                           PeriodStarts= l2.SelectMany( l => l.PeriodStart ),
                                           ResearchCredits = l2.SelectMany( l => l.ResearchCredit ) 
                                       })
                     .ToList();

这篇关于LINQ-合并多个列表以形成一个新列表并按键对齐它们吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆