Home > C# > Extension method fun

Extension method fun

During programming, I had the recurring need to find the positions of elements in a collection that satisfied a certain condition. Because duplication is evil, I wrote a small generic extension method to handle this.

public static class EnumerableExtensions
{
    public static IEnumerable<int> IndexesOf<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
    {
        IEnumerable<KeyValuePair<T, int>> keyValuePairs =
            enumerable.Select((item, index) => new KeyValuePair<T, int>(item, index));
        return keyValuePairs.Where(keyValue => predicate(keyValue.Key)).Select(keyValue => keyValue.Value);
    }
}

A small demo application, if you want to try it out:

class Program
{
    static void Main(string[] args)
    {
        string[] array = new string[] { "pieter", "bill", "steve", "philippe" };
        IEnumerable<int> indexes = array.IndexesOf(n => n.StartsWith("p"));

        Console.WriteLine("Indexes of names that start with a \"p\":");
        foreach (int index in indexes)
        {
            Console.WriteLine(index);
        }

        Console.ReadLine();
    }
}
Advertisements
Categories: C#
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: