📅  最后修改于: 2023-12-03 15:17:19.658000             🧑  作者: Mango
LINQ Distinct is a method that returns unique elements from a sequence. This method is used to remove duplicates from a collection or a list.
The syntax of the Distinct method is as follows:
IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source)
Where source
is an IEnumerable
of a specific data type TSource
.
Consider the following list of integers:
List<int> numbers = new List<int>{ 1, 2, 3, 4, 1, 2, 5 };
We want to remove duplicates from this list using the Distinct method. Let's see how this can be done:
var uniqueNumbers = numbers.Distinct();
The resulting uniqueNumbers
variable contains:
1, 2, 3, 4, 5
The Distinct
method uses the default equality comparer to check for duplicates. However, you can create a custom comparer to compare objects based on specific criteria.
For example, consider the following class:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
We want to remove duplicates from a list of persons based on their Name
property. We can create a custom comparer as follows:
public class PersonNameComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.Name == y.Name;
}
public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
To use this custom comparer with the Distinct
method, we need to pass it as a parameter:
List<Person> persons = new List<Person>
{
new Person { Id = 1, Name = "John", Age = 30 },
new Person { Id = 2, Name = "Mary", Age = 25 },
new Person { Id = 3, Name = "John", Age = 35 }
};
var uniquePersons = persons.Distinct(new PersonNameComparer());
The resulting uniquePersons
variable contains:
John, Mary
The Distinct
method is a useful LINQ method that helps remove duplicates from a collection or a list. It can also be used with a custom comparer to compare objects based on specific criteria.