LINQ#39;s Distinct() on a particular property(LINQ 在特定属性上的 Distinct())
问题描述
我正在使用 LINQ 来了解它,但是当我没有简单列表时,我不知道如何使用 Distinct(简单的整数列表很容易做到,这不是问题).如果我想使用 Distinct 在对象的一个或更多属性的对象列表上?
I am playing with LINQ to learn about it, but I can't figure out how to use Distinct when I do not have a simple list (a simple list of integers is pretty easy to do, this is not the question). What I if want to use Distinct on a list of an Object on one or more properties of the object?
示例:如果一个对象是Person,属性为Id.如何使用对象的属性 Id 获取所有 Person 并在其上使用 Distinct?
Example: If an object is Person, with Property Id. How can I get all Person and use Distinct on them with the property Id of the object?
Person1: Id=1, Name="Test1"
Person2: Id=1, Name="Test1"
Person3: Id=2, Name="Test2"
我怎样才能只得到 Person1 和 Person3?这可能吗?
How can I get just Person1 and Person3? Is that possible?
如果不能使用 LINQ,根据 .NET 3.5 中的某些属性,拥有 Person 列表的最佳方法是什么?
If it's not possible with LINQ, what would be the best way to have a list of Person depending on some of its properties in .NET 3.5?
推荐答案
编辑:这现在是 MoreLINQ.
您需要的是有效的distinct-by".我不相信它是 LINQ 的一部分,尽管它很容易编写:
What you need is a "distinct-by" effectively. I don't believe it's part of LINQ as it stands, although it's fairly easy to write:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
因此,要仅使用 Id 属性查找不同的值,您可以使用:
So to find the distinct values using just the Id property, you could use:
var query = people.DistinctBy(p => p.Id);
并且要使用多个属性,您可以使用匿名类型,它们可以适当地实现相等:
And to use multiple properties, you can use anonymous types, which implement equality appropriately:
var query = people.DistinctBy(p => new { p.Id, p.Name });
未经测试,但它应该可以工作(现在至少可以编译).
Untested, but it should work (and it now at least compiles).
它假定键的默认比较器 - 如果您想传入相等比较器,只需将其传递给 HashSet 构造函数.
It assumes the default comparer for the keys though - if you want to pass in an equality comparer, just pass it on to the HashSet constructor.
这篇关于LINQ 在特定属性上的 Distinct()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LINQ 在特定属性上的 Distinct()
基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
