[英]How to copy properties from one list to another using Linq conditionally
I have two lists of custom objects. 我有两个自定义对象列表。
Both have DivisionId
as common propery. 两者都将
DivisionId
作为通用属性。 I want to copy two parameters, PlanType
and CoverageType
, from List<Divisions>
to List<Members>
using Linq, whenever Member.DivisionId = Divisions.DivisionId
. 每当
Member.DivisionId = Divisions.DivisionId
时,我想使用Linq从List<Divisions>
复制两个参数PlanType
和CoverageType
到List<Members>
。
The Member and Divisions objects are given below : 成员和部门对象如下:
public class Members
{
public string FirstName;
public string LastName;
public string DivisionId;
}
Public Class Divisions
{
public string PlanType;
public string CoverageType,
public string DivisionId;
}
Thanks 谢谢
What you describe is Join 您描述的是加入
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
};
If you want to copy the item from index 0 in the first list to index 0 in the second, and so on for all of the other indexes you can do this: 如果要将项目从第一个列表的索引0复制到第二个列表的索引0,以此类推,对于所有其他索引,可以执行以下操作:
var pairs = members.Zip(divisions, (a, b) => new
{
Member = a,
Division = b,
});
foreach (var pair in pairs)
{
Copy(pair.Member, pair.Division);
}
If the indexes don't match you need to do a join: 如果索引不匹配,则需要进行联接:
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);
}
Note that the Zip
will be faster, if the items are already in the proper order. 请注意,如果物品已经按照正确的顺序放置,则
Zip
会更快。 Join will be slower than the Zip, but will be faster than manually re-ordering the items to allow a Zip
. Join将比Zip慢,但比手动重新排序项目以允许
Zip
快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.