链接通用列表扩展的方法

我有一个“复杂”类型的列表 – 一个具有一些字符串属性的对象。 List本身是另一个对象的属性,包含各种类型的对象,如此缩写类结构所示:

Customer { public List Characteristics; . . . } Characteristic { public string CharacteristicType; public string CharacteristicValue; } 

我希望能够为当前客户收集特定类型特征值的列表,我可以按如下步骤分两步完成:

 List interestCharacteristics = customer.Characteristics.FindAll( delegate (Characteristic interest) { return interest.CharacteristicType == "Interest"; } ); List interests = interestCharacteristics.ConvertAll( delegate (Characteristic interest) { return interest.CharacteristicValue; } ); 

这很好,但似乎还有很长的路要走。 我确定我必须错过一个更简单的方法来获取这个列表,或者通过链接FindAll()和Convert()方法,或者我完全忽略的其他东西。

对于背景,我在.Net 2.0工作,所以我只限于.Net 2generics,而且特性类是外部依赖 – 我不能改变它的结构来简化它,还有其他方面的这个重要的课程,与这个问题无关。

任何指针或额外的阅读欢迎。

这是一个生成器实现

 public static IEnumerable GetInterests(Customer customer) { foreach (Characteristic c in customer.Characteristics) { if (c.CharacteristicType == "Interest") yield return c.CharacteristicValue; } } 

遗憾的是,3.5扩展方法和lambda都是根据您的要求提出的,但是参考这里是如何做到的:

 customer.Characteristics .Where(c => c.CharacteristicType == "Interest") .Select(c => c. CharacteristicValue); 

我会手工完成一些工作。 通过首先执行FindAll,然后执行转换,您将循环遍历集合两次。 这似乎不是必要的。 如果你想在一天结束时,只需要一个CharacterValue列表,那么只需遍历原始集合,然后将CharacteristicValue添加到符合条件的每个列表中。 像这样的东西:

  Predicate criteria = delegate (Characteristic interest) { return interest.CharacteristicType == "Interest"; }; List myList = new List(); foreach(Characteristic c in customer.Characteristics) { if(criteria(c)) { myList.Add(c.CharacteristicValue); } } 

为什么不创建Dictionary> ,这样就可以添加“Interest”作为键,并将值列表作为值。 例如:

 Customer { public Dictionary> Characteristics; . . . } ... Characteristics.Add("Interest", new List()); Characteristics["Interest"].Add("Post questions on StackOverflow"); Characteristics["Interest"].Add("Answer questions on StackOverflow"); .. List interestCharacteristics = Characteristics["Interest"]; 

此外,如果您愿意,可以通过将其作为枚举将特征限制为可能值的列表,然后将其用作字典键的数据类型:

 public enum CharacteristicType { Interest, Job, ThingsYouHate //...etc } 

然后将您的字典声明为:

 public Dictionary> Characteristics; .. Characteristics.Add(CharacteristicType.Interest, new List()); Characteristics[CharacteristicType.Interest].Add("Post questions on StackOverflow"); Characteristics[CharacteristicType.Interest].Add("Answer questions on StackOverflow");