CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Collection Extensions

280 Views
Copy Code Show/Hide Line Numbers
/// <summary>
/// Find an object in a value-type collection.
/// </summary>
/// <typeparam name="T">Type of collection.</typeparam>
/// <param name="collection">The collection to search.</param>
/// <param name="isMatch">The Predicate to test to find the collection item.</param>
/// <returns>The collection item.</returns>
public static T GetValueItem<T>(this ICollection<T> collection, Predicate<T> isMatch)
{
    foreach (var item in collection)
    {
        if (isMatch(item))
            return item;
    }
    return default(T);
}
 
/// <summary>
/// Find an object in a reference type collection.
/// </summary>
/// <typeparam name="T">Type of collection.</typeparam>
/// <param name="collection">The collection to search.</param>
/// <param name="isMatch">The Predicate to test to find the collection item.</param>
/// <returns>The collection item.</returns>
public static T GetReferenceItem<T>(this ICollection<T> collection, Predicate<T> isMatch) where T : class, new()
{
    foreach (var item in collection)
    {
        if (isMatch(item))
            return item;
    }
    return new T();
}
by Bob Baker
  December 18, 2009 @ 12:00pm
Tags:
Description:
Wrote this to extend Value type and Reference Type collections to locate an item in testing

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate