VB.net Code to Compare Collections

Rajnilari2015
Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 666
Lets say we have two collections as under

Dim persons1 As New List(Of Person)() From { _
New Person() With { _
Key .Id = 1, _
Key .Name = "Person 1" _
}, _
New Person() With { _
Key .Id = 2, _
Key .Name = "Person 2" _
}, _
New Person() With { _
Key .Id = 3, _
Key .Name = "Person 3" _
}, _
New Person() With { _
Key .Id = 4, _
Key .Name = "Person 4" _
} _
}

Dim persons2 As New List(Of Person)() From { _
New Person() With { _
Key .Id = 1, _
Key .Name = "Person 1" _
}, _
New Person() With { _
Key .Id = 2, _
Key .Name = "Person 2" _
}, _
New Person() With { _
Key .Id = 3, _
Key .Name = "Person 3" _
}, _
New Person() With { _
Key .Id = 4, _
Key .Name = "Person 4" _
} _
}



Objective is to compare the collection. Below is the program to do so

If(persons1.Where(Function(x1) Not persons2.Any(Function(x2) x1.Id = x2.Id AndAlso x1.Name = x2.Name)).Union(persons2.Where(Function(x1) Not persons1.Any(Function(x2) x1.Id = x2.Id AndAlso x1.Name = x2.Name))).Count() = 0, Console.WriteLine("Collections are equal"), Console.WriteLine("Collections are not equal"))

Comments or Responses

Login to post response