I have two lists of custom objects.
Both have DivisionId
as common propery. I want to copy two parameters, PlanType
and CoverageType
, from List<Divisions>
to List<Members>
using Linq, whenever Member.DivisionId = Divisions.DivisionId
.
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:
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. Join will be slower than the Zip, but will be faster than manually re-ordering the items to allow a Zip
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.