检查两个列表的对象在特定属性及其索引方面是否相同
Check if the objects of two lists are identical with respect to specific properties and their index
考虑以下代码:
class MyType
{
public int Id { get; set; }
public string Text { get; set; }
public string DontCare { get; set; }
}
ICollection<MyType> list1 = new List<MyType>();
list1.Add(new MyType { Id = 1, Text = "first", DontCare="one" });
list1.Add(new MyType { Id = 2, Text = "second", DontCare = "two" });
ICollection<MyType> list2 = new List<MyType>();
list2.Add(new MyType { Id = 1, Text = "first", DontCare = "three" });
list2.Add(new MyType { Id = 2, Text = "second", DontCare = "four" });
我需要知道 list1
和 list2
中的对象是否相同,仅考虑属性 Id
和 Text
。列表的顺序是有保证的,所以 list1[0]
只需要与 list2[0]
进行比较,list1[1]
只需要与 list2[1]
进行比较。我如何在 C# 中做到这一点?
提示:这是一个简化的例子,list1
和 list2
可以是任意长度(尽管可以安全地假设它们具有相同的大小/否则短路)
如果索引像您所说的那样重要,您可以使用 Zip
+ Any
:
bool anyDifferent = list1
.Zip(list2, (l1, l2) => (l1, l2))
.Any(x => x.l1.Id != x.l2.Id || x.l1.Text != x.l2.Text);
或者 All
和相反的逻辑:
bool allIdentical = list1
.Zip(list2, (l1, l2) => (l1, l2))
.All(x => x.l1.Id == x.l2.Id && x.l1.Text == x.l2.Text);
两者具有相同的性能,因为它们 return 尽快得到结果。
考虑以下代码:
class MyType
{
public int Id { get; set; }
public string Text { get; set; }
public string DontCare { get; set; }
}
ICollection<MyType> list1 = new List<MyType>();
list1.Add(new MyType { Id = 1, Text = "first", DontCare="one" });
list1.Add(new MyType { Id = 2, Text = "second", DontCare = "two" });
ICollection<MyType> list2 = new List<MyType>();
list2.Add(new MyType { Id = 1, Text = "first", DontCare = "three" });
list2.Add(new MyType { Id = 2, Text = "second", DontCare = "four" });
我需要知道 list1
和 list2
中的对象是否相同,仅考虑属性 Id
和 Text
。列表的顺序是有保证的,所以 list1[0]
只需要与 list2[0]
进行比较,list1[1]
只需要与 list2[1]
进行比较。我如何在 C# 中做到这一点?
提示:这是一个简化的例子,list1
和 list2
可以是任意长度(尽管可以安全地假设它们具有相同的大小/否则短路)
如果索引像您所说的那样重要,您可以使用 Zip
+ Any
:
bool anyDifferent = list1
.Zip(list2, (l1, l2) => (l1, l2))
.Any(x => x.l1.Id != x.l2.Id || x.l1.Text != x.l2.Text);
或者 All
和相反的逻辑:
bool allIdentical = list1
.Zip(list2, (l1, l2) => (l1, l2))
.All(x => x.l1.Id == x.l2.Id && x.l1.Text == x.l2.Text);
两者具有相同的性能,因为它们 return 尽快得到结果。