开发者

LINQ - Combine multiple lists to form a new list and align them by key?

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 TradeBalanc开发者_C百科eBreak
{
    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; }
}

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.

Thanks.


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


var combined = from p in PhoneNumbers
               join a in Addresses on a.ID equals p.ID
               select new {
                   ID = p.ID,
                   Name = p.Name,
                   Phone = p.Phone,
                   Address = a.Address,
                   Fax = a.Fax
               };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜