Search code examples
c#listfindilist

How to add "Find" function to IList


I am returning IList from Business layer. But in viewmodel I have to use Find function. One method is to convert IList to List.

But is there anyway to add "Find" method to IList


Solution

  • Well, there are the Linq extension methods .Where (to fecth all that match) and .FirstOrDefault (to fetch the first match) or you can write your own extension method against IList like:

    public static class IListExtensions
    {
        public static T FindFirst<T>(this IList<T> source, Func<T, bool> condition)
        {
            foreach(T item in source)
                if(condition(item))
                    return item;
            return default(T);
        }
    }