在C#中判断两个列表数据是否相同

发布于:2025-07-27 ⋅ 阅读:(16) ⋅ 点赞:(0)

1. 使用SequenceEqual方法(顺序敏感)

List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 1, 2, 3 };

bool areEqual = list1.SequenceEqual(list2);
Console.WriteLine($"列表是否相同: {areEqual}"); // 输出: True

2. 不考虑顺序的比较(使用HashSet)

List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 3, 2, 1 };

bool areEqual = new HashSet<int>(list1).SetEquals(list2);
Console.WriteLine($"列表是否相同(不考虑顺序): {areEqual}"); // 输出: True

3. 使用LINQ All和Contains方法

List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 1, 2, 3 };

bool areEqual = list1.Count == list2.Count && list1.All(list2.Contains);
Console.WriteLine($"列表是否相同: {areEqual}"); // 输出: True

4. 自定义对象列表的比较(需要重写Equals和GetHashCode)

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public override bool Equals(object obj)
    {
        return obj is Person person && 
               Id == person.Id && 
               Name == person.Name;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Id, Name);
    }
}

// 使用
List<Person> people1 = new List<Person> { new Person { Id = 1, Name = "Alice" } };
List<Person> people2 = new List<Person> { new Person { Id = 1, Name = "Alice" } };

bool areEqual = people1.SequenceEqual(people2);
Console.WriteLine($"对象列表是否相同: {areEqual}"); // 输出: True

5. 使用Enumerable.Except方法

List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 1, 2, 3 };

bool areEqual = !list1.Except(list2).Any() && !list2.Except(list1).Any();
Console.WriteLine($"列表是否相同: {areEqual}"); // 输出: True

6. 性能考虑(大型列表)

对于大型列表,使用HashSet通常更高效:

List<int> bigList1 = Enumerable.Range(1, 100000).ToList();
List<int> bigList2 = Enumerable.Range(1, 100000).ToList();

var stopwatch = Stopwatch.StartNew();
bool areEqual = new HashSet<int>(bigList1).SetEquals(bigList2);
stopwatch.Stop();

Console.WriteLine($"大型列表比较结果: {areEqual}, 耗时: {stopwatch.ElapsedMilliseconds}ms");

7. 比较部分属性(使用LINQ)

如果只需要比较对象的某些属性:

List<Person> people1 = new List<Person> { new Person { Id = 1, Name = "Alice" } };
List<Person> people2 = new List<Person> { new Person { Id = 1, Name = "Alice" } };

bool areEqual = people1.Select(p => new { p.Id, p.Name })
                      .SequenceEqual(people2.Select(p => new { p.Id, p.Name }));

注意事项

1、顺序敏感:SequenceEqual会考虑元素的顺序

2、性能:对于大型列表,HashSet方法通常更高效

3、自定义对象:比较自定义对象时需要正确实现EqualsGetHashCode

4、重复元素:如果有重复元素,HashSet方法会认为[1,1,2][1,2,2]是相同的

5、空值处理:确保你的比较逻辑能正确处理null值


网站公告

今日签到

点亮在社区的每一天
去签到