我有两个自定义对象列表
两者都有DivisionId
作为共同的属性。我想在PlanType
时使用Linq将CoverageType
和List<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;
}
由于
答案 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
。