如何有条件地使用Linq将属性从一个列表复制到另一个列表

时间:2012-12-05 18:05:36

标签: c# linq

我有两个自定义对象列表 两者都有DivisionId作为共同的属性。我想在PlanType时使用Linq将CoverageTypeList<Divisions>两个参数从List<Members>复制到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;
}

由于

2 个答案:

答案 0 :(得分: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
                        };

答案 1 :(得分: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