LINQ VB 如何检查对象列表中的重复项
我有一个对象列表,每个对象都有 2 个相关属性:“ID”和“名称”。我们将该列表称为“lstOutcomes”。 我需要检查列表中是否有重复项(即 object1.ID = object2.ID
等),并设置一个标志(valid = false
等)(如果有)至少一份重复的。另外,当失败时,最好向用户发送一条消息,提及该对象的“名称”。
我确信我需要使用 Group By
运算符来执行此操作,但我不习惯在 LINQ 中执行此操作,并且那里的示例对我没有帮助。 这篇文章似乎接近我所需要的,但是不完全是,它是用 C# 编写的。
这是一个开始尝试......
Dim duplist = _
(From o As objectType In lstOutcomes _
Group o By o.ID Into g = Group _
Let dups = g.Where(Function(h) g.Count > 1) _
Order By dups Descending).ToArray
if duplist.count > 0 then
valid = false
end if
帮助?
I have a list of objects, each with 2 relevant properties: "ID" and "Name". Lets call the list "lstOutcomes".
I need to check the list for duplicates (meaning object1.ID = object2.ID
, etc.) and set a flag (valid = false
, or something) if there is at least one duplicate. Also, it would be nice to send a message to the user mentioning the "Name" of the object, when it fails.
I am sure I will need to use the Group By
operator to do this, but I am not used to doing that in LINQ, and the examples out there are just not helping me. This article seems to be close to what i need, but not quite and it's in C#.
Here is a starting stab at it...
Dim duplist = _
(From o As objectType In lstOutcomes _
Group o By o.ID Into g = Group _
Let dups = g.Where(Function(h) g.Count > 1) _
Order By dups Descending).ToArray
if duplist.count > 0 then
valid = false
end if
help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我将用 C# 编写它,但希望你能将它转换为 VB。它不使用 join,时间复杂度为 O(n log n),我假设您有
List
:I'll write it in C#, but hope you could convert it to VB. It does not use join and is O(n log n), and I assumed you have
List<T>
:虽然已经晚了,但它可以帮助其他人。
您可以通过一对非常干净的单行代码来实现这一点:
然后您可以清理重复项列表,以便它只包含一次重复项:
或者作为单行代码,尽管它读起来不太好
最后,作为预期对于未来的需求,您应该将“什么是重复项”定义为一个单独的事物。委托对此非常方便:
It is late, but though it could help others.
You can achieve this with a pair of very clean one-liners:
Then you can clean the list of duplicates so that it contains the duplicate only once:
Or as a one-liner, although it does not read as nicely
Finally, as an anticipation of future requirements, you should define "what a duplicate is" as a separate thing. A delegate is quite convenient for this:
我会收回 Saeed Amiri 在 C# 中所说的话并完成它。
I'll take back what Saeed Amiri said in C# and complete it.
该项目已经落后了,我只是将它拼凑在一起,如下所示:
The project is behind, I just hacked it together like this: