计算列表中对象属性的重复项

时间:2017-10-16 16:06:42

标签: vb.net

我整个下午都在寻找这个问题的答案而没有任何运气。

我声明了一个对象,并且它有许多属性。 e.g。

Public Class myObject
    Private _prop1 As String
    Private _prop2 As String
    Private _prop3 As String
    Private _prop4 As String


    Public Sub New(ByVal val1 As String _
           , ByVal val2 As String _
           , ByVal val3 As String _
           , ByVal val4 As String)
    _prop1 = val1
    _prop2 = val2
    _prop3 = val3
    _prop4 = val4
    End Sub

    Public Property Prop1() As String
    Get
        Return _prop1
    End Get
    Set(ByVal value As String)
        _prop1 = value
    End Set
    End Property

    Public Property Prop2() As String
    Get
        Return _prop2
    End Get
    Set(ByVal value As String)
        _prop2 = value
    End Set
    End Property

    Public Property Prop3() As String
    Get
        Return _prop3
    End Get
    Set(ByVal value As String)
        _prop3 = value
    End Set
    End Property

    Public Property Prop4() As String
    Get
        Return _prop4
    End Get
    Set(ByVal value As String)
        _prop4 = value
    End Set
    End Property
End Class

在我的代码中,我有这些对象的列表:

Dim myList as List(of myObject)

然后我填写列表......

{根据要求,它有点像这样,即使填充它的方法无关紧要: - )}

Dim myFile as String = readFile(myFilename)
Dim fileLines() as String = Split(myFile,vbCrLf)
Dim splitLine() as String
For each line in fileLines
    splitLine = Split(line,"|")
    myList.add(new myObject(splitLine(0),splitLine(1),splitLine(2),splitLine(3))
 Next

我需要的是一个列表,其中所有Prop1值都是唯一的,因此我希望能够识别myList.Prop1中的任何重复值

我已经尝试了Finding Duplicates based On A Property In Object,但这似乎并没有违法。

我故意用一个已知副本创建列表。使用上述问题的改编代码......

Dim duplicates = myList.GroupBy(Function(i) i.Prop1) _
                        .Where(Function(x) x.Count() > 1) _
                        .[Select](Function(x) x)

...导致重复是"没有",即使有一个。

在这个阶段,我不需要确定重复项,只是它们在那里。但是,如果直接合并此功能比我想要添加它。

1 个答案:

答案 0 :(得分:1)

获取所有重复对象相当简单,看一下这个例子:

Dim myList as List(Of myObject) = New List(Of myObject)

'Add arbitrary values (demo only)
myList.AddRange({New myObject("A", "B", "C", "D"), New myObject("A", "C", "D", "E"), New myObject("B", "C", "D", "E"), New myObject("C", "D", "E", "F")})

'Get all objects where Prop1 is the same
Dim duplicateProp1 = (From o As myObject in myList Group By Prop1 = o.Prop1 Into g = Group Where g.Count > 1 Select g.FirstOrDefault())

'Print all the duplicate objects (demo only)
For Each d As myObject In duplicateProp1
    Console.WriteLine(d.Prop1)
Next

小提琴:Live Demo