ExtensionMethod.NET Home of 819 C#, Visual Basic, F# and Javascript extension methods

Filter

Allows you to filter an IEnumerable<T>

Source

public static IEnumerable<T> Filter<T>(this IEnumerable<T> list, Func<T, bool> filterParam) {
    return list.Where(filterParam);
}

Example

static void Main() {

    var items = new List<TestItem> {
            new TestItem {ItemID = 1, ItemName = "TestItem"},
            new TestItem {ItemID = 2, ItemName = "Wigit"},
            new TestItem {ItemID = 3, ItemName = "TestItem2"},
            new TestItem {ItemID = 4, ItemName = "Foo"},
            new TestItem {ItemID = 5, ItemName = "Bar"},
            new TestItem {ItemID = 6, ItemName = "TestFooBarItem"}
    };

    Console.WriteLine("Items starting with Test using delegate");
    Func<TestItem, bool> itemNameFilter = delegate(TestItem testItem) { return testItem.ItemName.StartsWith("Test"); };
    foreach (var testItem in items.Filter(itemNameFilter)) {
        Console.WriteLine(testItem.ItemName);
    }

    Console.WriteLine("Items with ItemName containing Item and ItemID > 2 using Lamda Expression");
    foreach (var testItem in items.Filter(x => x.ItemName.StartsWith("Test") && x.ItemID > 2)) {
        Console.WriteLine(testItem.ItemName);
    }

    Console.ReadLine();
}

Author: Jeff Reddy

Submitted on: 9 aug 2011

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 5790