Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I really don't quite understand this kind of using this, what's its function and benefit?
C#
public static T FirstOrDefault<T>(this IEnumerable<T> sequence, Predicate<T> test)
{
    foreach (T value in sequence)
        if (test(value))
            return value;
    return default(T);
} 
Posted
Comments
qinritukou 21-May-12 20:49pm    
Hi, guys.Thank you very much for your help.

It's an extension method

http://msdn.microsoft.com/en-us/library/bb383977.aspx[^]

It allows you to define 'custom methods' as if they are part of a particular object.
 
Share this answer
 
Comments
Wonde Tadesse 21-May-12 20:14pm    
5+
That is quite obvious. Here you have a generic method that will return a type of object/value that you specify in your code. So your code will be typesafe and you will not be forced to rewrite the code for every new type you introduce. A predicate is just a function that returns true or false and by supplying such a function to this method you can specify the criterion of what to return simply by detecting this in the predicate function and returning true when the criterion is met. Since the method only demands an IEnumerable<T> you can pass pretty much every Collection of objects/values into it, so this makes the usage of said method very flexible.

Any doubts left?

Regards,

Manfred
 
Share this answer
 
v2
Comments
Wonde Tadesse 21-May-12 20:21pm    
5+
this might be helpful,

FirstOrDefault[^] and read the rest of the article which might help you to understand it.

Hope it helps :)
 
Share this answer
 
Comments
Wonde Tadesse 21-May-12 20:21pm    
5+
Mohammad A Rahman 21-May-12 20:24pm    
Thank you, I hope you might like my article :)
It's an extension method to a generic IEnumerable which returns the first value which passes a supplied test, or returns the default value if no such value is found.

What you can do with it is call it on any generic collection (such as a List, or an array) which a specific test method supplied and it will give you the appropriate value.

For example:
C#
List<string> list = new List<string>();
list.Add("hello");
list.Add("goodbye");
string f = list.FirstOrDefault(v => v.StartsWith("h"));
Will give me f containing "hello".
If I hadn't added "hello" to the list of strings, f would be null - the default value for a uninitialised string.
 
Share this answer
 
Comments
Wonde Tadesse 21-May-12 20:21pm    
5+

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900