BrettNelson
Member
- Joined
- Apr 8, 2016
- Messages
- 11
- Programming Experience
- Beginner
The code below, specifically Sub Button1_Click, creates a distinct list (distinctList) of values from the List(Of MainObject).
My question is - even though it produces the exact results I'm looking for, the logic seems cluttered. Anyone know of a cleaner or more direct way to create this distinct list of MainList.Prop2?
My question is - even though it produces the exact results I'm looking for, the logic seems cluttered. Anyone know of a cleaner or more direct way to create this distinct list of MainList.Prop2?
VB.NET:
Public Class Form1
Private MainList As New List(Of MainObject)
Public Sub New()
InitializeComponent()
MainList.Add(New MainObject With {.Prop1 = "1", .Prop2 = "val 1"})
MainList.Add(New MainObject With {.Prop1 = "2", .Prop2 = "val X"})
MainList.Add(New MainObject With {.Prop1 = "1", .Prop2 = "val 1"}) ' "val 1" is a Duplicate
MainList.Add(New MainObject With {.Prop1 = "1", .Prop2 = "val N"})
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim distinctList As New List(Of OnePropObj)
For Each itm As MainObject In MainList
Dim findObj As New OnePropObj
findObj = distinctList.FirstOrDefault(Function(xx) xx.ValueX = itm.Prop2)
If findObj Is Nothing Then
distinctList.Add(New OnePropObj With {.ValueX = itm.Prop2}) ' this line loads the distinctList
End If
Next
' when flow arrives here (distinctList) holds/stores the correct data, 3 elements
End Sub
Private Class OnePropObj
Public Property ValueX As String
End Class
Private Class MainObject
Public Property Prop1 As String
Public Property Prop2 As String
End Class
End Class
Last edited by a moderator: