0

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?

4

2 回答 2

8

Select()第一的...

var ids = array.Select(o => o.ID).Distinct();

编辑:

你好,能否解释一下原因。

首先,让我们谈谈你做错了什么:

var ids = array.ID.Distinct();
  1. 您试图引用数组ID中不存在的成员。您正在寻找的是数组中的一个项目。ID
  2. 您试图调用Distinct()那个不存在的成员而不是collection

现在让我们看看新代码做了什么:

var ids = array.Select(o => o.ID).Distinct();

Select()会生成一个仅产生ID值的新枚举。Distinct()生成另一个可枚举,仅产生来自Select().

于 2013-09-27T17:22:53.097 回答
3

HashSet如果您打算继续进行查找,请使用 a :

var hashSet = new HashSet<int>(array.Select(i => i.ID));

这将自动删除重复项并允许接近 O(1) 查找。

于 2013-09-27T17:26:54.700 回答