Reputation: 4434
Let's say I work at the Dept. of Health. I've processed food poisoning complaints and stored the complaints data into a multi-dimensional array like so:
Array[0] contains the first complaint's data. Array[0].ID contains the restaurant ID of the first complaint and so forth.
Within my array how do I extract a list of unique 5 digit IDs?
Some restaurants might have 50 complaints and some might have just 1. I want to create a list of all of the unique restaurant IDs that show up in my complaints data.
var Unique = array.ID.Distinct();
does not work. What am I doing wrong?
Upvotes: 0
Views: 169
Reputation: 41665
Select()
first...
var ids = array.Select(o => o.ID).Distinct();
Edit:
Hi, can you please explain why.
First, let's talk about what you did wrong:
var ids = array.ID.Distinct();
ID
, a non-existent member of the array. What you're looking for is the ID
of an item within the array.Distinct()
on that non-existent member rather than the collection.Now let's look at what the new code does:
var ids = array.Select(o => o.ID).Distinct();
That Select()
generates a new enumerable yielding only the ID
values. The Distinct()
generates another enumerable, yielding only the unique values from the Select()
.
Upvotes: 8
Reputation: 34782
Use a HashSet
if you plan to do lookups going forward:
var hashSet = new HashSet<int>(array.Select(i => i.ID));
This will automatically remove duplicates and also allow near O(1) lookups.
Upvotes: 3