📜  如何在 c# 中的 linq 查询中使用 distinct(1)

📅  最后修改于: 2023-12-03 15:38:13.673000             🧑  作者: Mango

如何在 C# 中的 LINQ 查询中使用 DISTINCT

LINQ (Language Integrated Query) 是 C# 中强大的查询语言,可以方便地查询内存中的对象集合、数据表、XML 等等,还可以进行分组、排序、聚合等操作。有时候我们需要对查询结果进行去重,这时候可以使用 DISTINCT 关键字来实现。

简单去重

下面给出一个简单的示例代码,查询一个整数列表中的不重复元素:

List<int> nums = new List<int> {1, 2, 2, 3, 3, 3, 4, 5, 5};
var distinctNums = nums.Distinct();
foreach (var num in distinctNums)
{
    Console.WriteLine(num);
}

输出结果为:

1
2
3
4
5

代码片段:

List<int> nums = new List<int> {1, 2, 2, 3, 3, 3, 4, 5, 5};
var distinctNums = nums.Distinct();
foreach (var num in distinctNums)
{
    Console.WriteLine(num);
}
复杂对象去重

如果我们需要对复杂的对象集合进行去重,需要指定按照哪个属性进行比较。下面是一个示例代码,对一个包含多个学生对象的集合进行去重:

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Student> students = new List<Student> 
{
    new Student {Name = "Tom", Age = 18},
    new Student {Name = "Tom", Age = 18},
    new Student {Name = "Jerry", Age = 19}
};

var distinctStudents = students.Distinct(new StudentComparer());
foreach (var student in distinctStudents)
{
    Console.WriteLine($"Name:{student.Name}, Age:{student.Age}");
}

class StudentComparer : IEqualityComparer<Student>
{
    public bool Equals(Student x, Student y)
    {
        return x.Name.Equals(y.Name) && x.Age == y.Age;
    }
    public int GetHashCode(Student obj)
    {
        return obj.Name.GetHashCode() ^ obj.Age;
    }
}

输出结果为:

Name:Tom, Age:18
Name:Jerry, Age:19

代码片段:

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Student> students = new List<Student> 
{
    new Student {Name = "Tom", Age = 18},
    new Student {Name = "Tom", Age = 18},
    new Student {Name = "Jerry", Age = 19}
};

var distinctStudents = students.Distinct(new StudentComparer());
foreach (var student in distinctStudents)
{
    Console.WriteLine($"Name:{student.Name}, Age:{student.Age}");
}

class StudentComparer : IEqualityComparer<Student>
{
    public bool Equals(Student x, Student y)
    {
        return x.Name.Equals(y.Name) && x.Age == y.Age;
    }
    public int GetHashCode(Student obj)
    {
        return obj.Name.GetHashCode() ^ obj.Age;
    }
}
总结

使用 DISTINCT 关键字可以轻松地对 LINQ 查询结果进行去重,对于复杂对象集合需要自定义比较器。