Reputation: 651
I have this problem
Structure Person
Dim name As String
Dim age As Integer
End Structure
Dim people(10) As Person
people(0).name = "A"
people(0).age = 21
...
people(9).name = "Z"
people(9).age = 30
Now e.g. if I have the following values for age = {20, 21, 20, 23, 25, 35, 30, 29, 25, 26}
I am trying to identify and eliminate every person from people
who has a unique age, i.e., my final people
array should only contain records of persons with ages 20,25
.
I tried something like this:
tempList() As Int
cleanList() As Int
for i = 0 to people.count - 1
array.resize(templist, i + 1)
templist(i) = people(i).age
next
cleanList = tempList.Distinct().ToArray()
The problem is, doing it this way gives me each and every distinct value from the array. But I want only those values which occur only once.
Any help on this?
Thanks a lot!
Upvotes: 0
Views: 341
Reputation: 22876
You can group by .age
and get the items from the groups that have more than one item:
Dim cleanList = people.ToLookup(Function(p) p.age).
Where(Function(g) g.Count > 1).SelectMany(Function(g) g).ToList
Upvotes: 1
Reputation: 1507
Try this:
Dim duplicatePersons = people.Where(Function(p) people.Count(Function(p1) p1.Age = p.Age) > 1).ToArray()
Upvotes: 0
Reputation: 39346
You need to group your list of ages first to get only the repeated values:
Dim ages= From a In allages _
Group a By Key = a Into Group _
Where Group.Count() > 1 _
Select Group.Key
Then you can filter you list of people:
Dim result = From p In people _
Where ages.Contains(p.age) _
Select p
Upvotes: 0