Home
Manage Your Code
Snippet: Generic Pluck (C#)
Title: Generic Pluck Language: C#
Description: Generic version of the other Pluck method I posted Views: 632
Author: Chris Carter Date Added: 9/11/2006
Copy Code  
1public class PluckableList<T> : List<T>{
2  public Array Pluck(string propertyName){
3    Type type = typeof(T);
4    PropertyInfo property = type.GetProperty(propertyName);
5    Array result = Array.CreateInstance(property.PropertyType, this.Count);
6    for(int i=0;i<this.Count;i++){
7      result.SetValue(type.InvokeMember(propertyName, BindingFlags.GetProperty, null, this[i], null), i);
8    }
9    return result;
10  }
11}
Usage
      PluckableList<Person> peeps = new PluckableList<Person>();
      peeps.Add(new Person("Chris", "Carter", 666));
      peeps.Add(new Person("Anja", "Carter", 1));
      peeps.Add(new Person("Riley", "Carter", 2));
      string[] firstNames = (string[])peeps.Pluck("FirstName");
      foreach(string firstName in firstNames){
        Console.WriteLine(firstName);
      }
      int[] ids = (int[])peeps.Pluck("ID");
      foreach(int id in ids){
        Console.WriteLine(id);
      }