Generics and Anonymous Methods/Delegates make up a powerful pair that can be used to create elegant query APIs. Here are some that we just added to the .NET Framework’s Collection libraries. I used List<T> to illustrate the APIs but most of those were also added to System.Array.

API Design

Delegates

namespace System {

   public delegate void Action<T>(T obj);

   public delegate bool Predicate<T>(T obj);

   public delegate U Converter<T,U>(T from);

   public delegate int Comparison<T>(T x, T y);

}

List<T>

public class List<T> : … {

   public int FindIndex(Predicate<T> match);

   public int FindIndex(int index, Predicate<T> match);

   public int FindIndex(int index, int count, Predicate<T> match);

   public int FindLastIndex(Predicate<T> match);

   public int FindLastIndex(int index, Predicate<T> match);

   public int FindLastIndex(int index, int count, Predicate<T> match);

 

   public List<T> FindAll(Predicate<T> match);

   public T Find(Predicate<T> match);

   public T FindLast(Predicate match);

   public bool Exists(Predicate<T> match);

   public bool TrueForAll(Predicate<T> match); 

   public int RemoveAll(Predicate<T> match);

   public void ForEach(Action<T> action);

   public void Sort(Comparison<T> comparison);

   public List<U> ConvertAll<U>(Converter<T,U> converter);

}

Finding Even Integers in List<T>

List<int> integers = new List<int>();

For(int i=1; i<=10; i++) integers.Add(i);

List<int> even = integers.FindAll(delegate(int i){

   return i%2==0;

});

Finding Complex Type in List<T>

public class Order {

   public Order(int number, string item) { … }

   public int Number { get { return number; } }

   public string Item { get { return item; } }

   …

}

List<Order> orders = new List<Order>();

int orderNumber = 10;

Order order = orders.Find(delegate(Order o){

   return o.Number==orderNumber;

});

Computing Sum of Integers in List<T>

List<int> integers = new List<int>();

for(int i=1; i<=10; i++) integers.Add(i);

int sum;

integers.ForEach(delegate(int i){ sum+=i; });

Sort Orders in List<T>

List<Order> orders = new List<Order>();

orders.Add(new Order(10,”Milk”));

orders.Add(new Order(5,”Cheese”));

 orders.Sort(delegate(Order x, Order y){

   return Comparer<int>.Default.Compare(x.Number,y.Number);

});

Convert Orders to Order Numbers

List<Order> orders = new List<Order>();

orders.Add(new Order(10,”Milk”));

orders.Add(new Order(5,”Cheese”));

List<int> numbers = orders.ConvertAll(delegate(Order x){

   return o.Number;

});