是否有 Linq 操作来确定集合中是否存在具有相同属性值的项目?

发布于 2024-08-08 21:03:38 字数 306 浏览 3 评论 0原文

C#:我有一个对象集合。 T 有 2 个属性。属性 A 和属性 B。该集合需要遵守的规则是 A 和 B 的值的组合在集合中必须是唯一的。换句话说,A和B需要作为复合主键。

我可以使用 Linq 中的操作来检查此情况吗?我希望它类似于

if (items.Select(x => x.Name).Distinct().Count() != items.Select(x => x.Name).Count())

上面的语句,我将如何检查集合中是否存在具有重复名称的项目,但我不知道如何对多个属性执行此操作。

C#: I have a collection of objects . T has 2 properties. Property A and Property B. The rule that this collection needs to adhere to is that the combination of values for A and B must be unique within the collection. In other words, A and B need to serve as a composite primary key.

Is there an operation in Linq I can use to check this condition? I'd expect it to be something like

if (items.Select(x => x.Name).Distinct().Count() != items.Select(x => x.Name).Count())

The above statement is how I would check whether there are items in the collection which have duplicate Names, but I don't know how to do it for more than one property.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

黒涩兲箜 2024-08-15 21:03:38

使用匿名类型来选择复合键,例如,

int totalCount = items.Count();
int distinctCount = items.Select(x => new { x.Name, x.Other })
                         .Distinct()
                         .Count();

匿名类型根据其属性(以及这些属性的类型的默认相等比较器)自动实现相等性和哈希码。

Use an anonymous type to select the composite key, e.g.

int totalCount = items.Count();
int distinctCount = items.Select(x => new { x.Name, x.Other })
                         .Distinct()
                         .Count();

Anonymous types automatically implement equality and hashcodes based on their properties (and the default equality comparer for the types of those properties).

云柯 2024-08-15 21:03:38

只需选择一个新的匿名对象

var keys = items.Select( x => new { x.Name, x.Other } ).ToList();

if (keys.Distinct().Count() != keys.Count())
{
 ...
}

Simply select into a new, anonymous object

var keys = items.Select( x => new { x.Name, x.Other } ).ToList();

if (keys.Distinct().Count() != keys.Count())
{
 ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文