MrPatterns
MrPatterns

Reputation: 4434

How do I identify unique properties of elements within my array?

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:

  1. ID - 5 digit ID number for the restaurant victim ate at
  2. Date - Date of Food Poisoning
  3. Name - Name of Victim
  4. Age - Age of Victim
  5. Phone - Victim's Phone Number

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

Answers (2)

canon
canon

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();
  1. You tried to refer to ID, a non-existent member of the array. What you're looking for is the ID of an item within the array.
  2. You tried to call 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

Haney
Haney

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

Related Questions