【发布时间】:2017-07-14 09:08:11
【问题描述】:
我有两个具有相同值的集合,但它们具有不同的引用。在没有 foreach 语句的情况下比较两个集合的最佳方法是什么, 下面是我创建的示例应用程序,
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace CollectionComparer
{
public class Program
{
private static void Main(string[] args)
{
var persons = GetPersons();
var p1 = new ObservableCollection<Person>(persons);
IList<Person> p2 = p1.ToList().ConvertAll(x =>
new Person
{
Id = x.Id,
Age = x.Age,
Name = x.Name,
Country = x.Country
});
//p1[0].Name = "Name6";
//p1[1].Age = 36;
if (Equals(p1, p2))
Console.WriteLine("Collection and its values are Equal");
else
Console.WriteLine("Collection and its values are not Equal");
Console.ReadLine();
}
public static IEnumerable<Person> GetPersons()
{
var persons = new List<Person>();
for (var i = 0; i < 5; i++)
{
var p = new Person
{
Id = i,
Age = 20 + i,
Name = "Name" + i,
Country = "Country" + i
};
persons.Add(p);
}
return persons;
}
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Country { get; set; }
}
在上面的代码中,我需要比较集合 p1 和 p2。但结果总是出现“集合及其值不相等”,因为两个集合具有不同的参考。 有没有一种通用的方法来进行这种比较而不使用 foreach 并比较类型特定的属性。
【问题讨论】:
-
你可以为你的
Person类覆盖Equals -
为什么不想使用 foreach 循环?那么 for 循环呢?
-
顺序重要还是要检查两个集合中的人物是否相同?
-
比如你有两个
List<Person>p1和p2。var areEqual = p1.All(p => p2.Contains(p); -
这里的顺序并不重要。我只想检查一个项目是否在一个集合中添加、删除或编辑。
标签: c# .net generics collections reference