是否有 Linq 操作来确定集合中是否存在具有相同属性值的项目?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用匿名类型来选择复合键,例如,
匿名类型根据其属性(以及这些属性的类型的默认相等比较器)自动实现相等性和哈希码。
Use an anonymous type to select the composite key, e.g.
Anonymous types automatically implement equality and hashcodes based on their properties (and the default equality comparer for the types of those properties).
您可以注入自己的相等比较器。例子在这里:
http://social .msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/c5b71644-b2d9-422b-b7fe-ef3bef30bbac/
You can inject your own equality comparer. Example is here:
http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/c5b71644-b2d9-422b-b7fe-ef3bef30bbac/
只需选择一个新的匿名对象
Simply select into a new, anonymous object