我玩LINQ来了解它,但我不知道如何使用鲜明当我没有一个简单的列表(一个简单的整数列表是很容易做到的,这不是问题)。如果我想使用鲜明的列表<TElement>上的一个或多个属性的TElement?
示例:如果一个对象是Person,具有属性Id。我怎么能得到所有人,并使用鲜明对他们与对象的属性Id ?
Person1: Id=1, Name="Test1"
Person2: Id=1, Name="Test1"
Person3: Id=2, Name="Test2"
如何得到Person1和Person3?这可能吗?
如果用LINQ是不可能的,那么根据Person的某些属性获得Person列表的最佳方法是什么?
重写Equals(object obj)和GetHashCode()方法:
class Person
{
public int Id { get; set; }
public int Name { get; set; }
public override bool Equals(object obj)
{
return ((Person)obj).Id == Id;
// or:
// var o = (Person)obj;
// return o.Id == Id && o.Name == Name;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
然后调用:
List<Person> distinctList = new[] { person1, person2, person3 }.Distinct().ToList();
从。net 6开始,在Linq中使用新的DistinctBy()扩展有了新的解决方案,所以我们可以做:
var distinctPersonsById = personList.DistinctBy(x => x.Id);
DistinctBy方法的签名:
// Returns distinct elements from a sequence according to a specified
// key selector function.
public static IEnumerable<TSource> DistinctBy<TSource, TKey> (
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector);
我写了一篇文章,解释了如何扩展Distinct函数,这样你就可以这样做:
var people = new List<Person>();
people.Add(new Person(1, "a", "b"));
people.Add(new Person(2, "c", "d"));
people.Add(new Person(1, "a", "b"));
foreach (var person in people.Distinct(p => p.ID))
// Do stuff with unique list here.
这是一篇文章(现在在Web档案中):扩展LINQ -在Distinct函数中指定属性