0

我有两个自定义对象列表。
两者都有DivisionId共同的属性。我想复制两个参数,PlanTypeCoverageType,从List<Divisions>使用List<Members>Linq,无论何时Member.DivisionId = Divisions.DivisionId

成员和部门对象如下:

public class Members
{
  public string FirstName;
  public string LastName;
  public string DivisionId;
}

Public Class Divisions
{
  public string PlanType;
  public string CoverageType,
  public string DivisionId;
}

谢谢

4

2 回答 2

0

你描述的是加入

    var query = from m in members
                join d in divisions on m.DivisionId equals d.DivisionId
                select new { m.FirstName,
                            m.LastName,
                            m.DivisionId,
                            d.CoverageType,
                            d.PlanType
                        };
于 2012-12-05T18:12:30.290 回答
0

如果要将项目从第一个列表中的索引 0 复制到第二个列表中的索引 0,以此类推,对于所有其他索引,您可以这样做:

var pairs = members.Zip(divisions, (a, b) => new
{
    Member = a,
    Division = b,
});

foreach (var pair in pairs)
{
    Copy(pair.Member, pair.Division);
}

如果索引不匹配,您需要进行连接:

var pairs = members.Join(divisions
    , member => member.DivisionId
    , division => division.DivisionId
    , (a, b) => new
    {
        Member = a,
        Division = b,
    });

foreach (var pair in pairs)
{
    Copy(pair.Member, pair.Division);
}

请注意Zip,如果项目已经按正确的顺序排列,将会更快。加入将比 Zip 慢,但会比手动重新排序项目以允许Zip.

于 2012-12-05T18:12:50.673 回答