LINQ VB如何检查对象列表中的重复项 [英] LINQ VB how to check for duplicates in a list of objects
问题描述
我有一个对象列表,每个对象都有2个相关属性:"ID"和名称".让我们将列表称为"lstOutcomes".
我需要检查列表中是否存在重复项(表示object1.ID = object2.ID
等),如果至少有一个重复项,则设置一个标志(valid = false
等).同样,当对象失败时,向用户发送一条消息,提及对象的名称"也是很好的选择.
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.
我确定我将需要使用Group By
运算符来执行此操作,但是我不习惯在LINQ中执行此操作,并且那里的示例只是对我没有帮助. 这篇文章似乎很接近我的需要,但是不完全是,它在C#中.
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
帮助?
推荐答案
项目在后面,我只是这样将其砍死:
The project is behind, I just hacked it together like this:
' For each outcome, if it is in the list of valid outcomes more than once, and it is not in the list of
' duplicates, add it to the duplicates list.
Dim lstDuplicates As New List(Of objectType)
For Each outcome As objectType In lstOutcomes
'declare a stable outcome variable
Dim loutcome As objectType = outcome
If lstOutcomes.Where(Function(o) o.ID = loutcome.ID).Count > 1 _
AndAlso Not lstDuplicates.Where(Function(d) d.ID = loutcome.ID).Count > 0 Then
lstDuplicates.Add(outcome)
End If
Next
If lstDuplicates.Count > 0 Then
valid = False
sbErrors.Append("There cannot be multiple outcomes of any kind. The following " & lstDuplicates.Count & _
" outcomes are duplicates: ")
For Each dup As objectType In lstDuplicates
sbErrors.Append("""" & dup.Name & """" & " ")
Next
sbErrors.Append("." & vbNewLine)
End If
这篇关于LINQ VB如何检查对象列表中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!