Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add "Find" function to IList

Tags:

c#

find

list

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

like image 867
Relativity Avatar asked Nov 14 '10 02:11

Relativity


People also ask

How do I add AddRange to IList?

You can declare the variable as List<T> instead of IList<T> or cast it to List<T> in order to gain access to AddRange .

How do you check if a value exists in a list C#?

public bool Contains (T item); Here, item is the object which is to be locate in the List<T>. The value can be null for reference types. Return Value: This method returns True if the item is found in the List<T> otherwise returns False.

What does find return if nothing is found C#?

Find() would return null when the condition wasn't satisfied.


1 Answers

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);
    }
}
like image 104
scmccart Avatar answered Oct 20 '22 00:10

scmccart