假设我有一个Person
类,我有两个Person
集合实例,第一个实例是包含所有记录的主集合,而第二个实例是主集合的子集
我需要做的是更新主集中的IsMatched属性,其中实例也存在于子集中。
public class Person
{
public int Id { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsMatched { get; set; }
}
可以使用可枚举Intersect或Any来匹配和更新主数据集吗?
根据蒂姆的建议,我创建了一个单元测试来测试解决方案
[TestFixture()]
public class Test
{
[TestFixture]
public class MatchedSetTest
{
private class Person
{
public int Id { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsMatched { get; set; }
}
[Test]
public void TestMatchingSets()
{
var members = new List<Person>()
{
new Person() { FirstName = "Tom", LastName = "Smith", Id = 1, Title = "Mr", IsMatched = false} ,
new Person() { FirstName = "Paul", LastName = "Jones", Id = 2, Title = "Mr", IsMatched = false} ,
new Person() { FirstName = "Gary", LastName = "Thompson", Id = 3, Title = "Mr", IsMatched = false} ,
new Person() { FirstName = "Simon", LastName = "Green", Id = 4, Title = "Mr", IsMatched = false} ,
new Person() { FirstName = "Phil", LastName = "Stuart", Id = 5, Title = "Mr", IsMatched = false} ,
new Person() { FirstName = "Sean", LastName = "Appleton", Id = 6, Title = "Mr", IsMatched = false}
};
var buddy = new List<Person>()
{
new Person() { FirstName = "Tom", LastName = "Smith", Id = 1, Title = "Mr", IsMatched = false} ,
new Person() { FirstName = "Gary", LastName = "Thompson", Id = 3, Title = "Mr", IsMatched = false} ,
new Person() { FirstName = "Simon", LastName = "Green", Id = 4, Title = "Mr", IsMatched = false}
};
var existing = from m in members
join s in buddy on m.Id equals s.Id
select new { Master = m, Subset = s };
foreach (var both in existing)
{
both.Master.IsMatched = both.Subset.IsMatched;
}
var p = existing.Where(w => w.Master.Id == 1).FirstOrDefault().Master;
Assert.IsTrue(p.IsMatched);
}
}
}
现有对象包含子集中的三个项目,其中包含Master和Subset实例,并且所有实例的IsMatched属性仍为False。
我需要的是返回整个Master集合,并在匹配的Master集合实例上将标记IsMatched属性的子集中的匹配项返回true。
另一个选项
这是一个合适的解决方案吗?
buddy.ForEach(b =>
{
var member = members.FirstOrDefault(w => w.Id == b.Id);
if (member != null)
member.IsMatched = true;
});
答案 0 :(得分:1)
您可以加入它们,以匿名方式存储,然后使用foreach:
var existing = from m in master join s in subset on m.Id equals s.Id
select new { Master = m, Subset = s };
foreach (var both in existing)
{
both.Master.IsMatched = both.Subset.IsMatched;
}
请注意,这假设每个主服务器只有一个子集。如果你有重复项,结果可能是任意的,因为最后一个子集人获胜。
答案 1 :(得分:0)
在单元测试中使用
var existing = from m in members
join s in buddy on m.Id equals s.Id
select new { Master = m, Subset = s };
foreach (var both in existing)
{
both.Master.IsMatched = true;
}
答案 2 :(得分:-1)
以下代码段仅返回personListA
中存在的personListB
中的记录,personListB
中的匹配记录IsMatched
设置为true(匹配记录基于在Id
属性上。
personListA.Where(pla => personListB.Any(plb => plb.Id == pla.Id && plb.IsMatched));