Yes, First() is one extension method which has overloads also how to use these overloads
we will see now
public static TSource First<TSource>(this IEnumerable<TSource> source);
public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
First: Retrieves the first occurrence
we will see now
public static TSource First<TSource>(this IEnumerable<TSource> source);
public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
First: Retrieves the first occurrence
Ex1:
int[] intarr1 = new int[5];
intarr1[0] = 150;
intarr1[1] = 80;
intarr1[2] = 25;
intarr1[3] = 150;
intarr1[4] = 14;
int i = intarr1.First<int>();
int j = intarr1.First<int>(x => x == 25); // matching so no error
// not matching value throug exception so go for FirstOrDefault.
int k = intarr1.FirstOrDefault<int>(x => x == 125);
// not matching even no error by because we uses FirstOrDefault extension method
Console.WriteLine(i);
Console.WriteLine(j);
Console.WriteLine(k);
int l = intarr1.FirstOrDefault();
Console.WriteLine(l);
Output:150,
25
0[zero]-no matching[if matching returns same value.
150---l value.
Here i means in total collection or array FirstElement returns;
Imp Notes:
Here j means in total collection or array Matching Element of Conditation Only.
Here m menas in total collection or array matching Element is not found returns default value 0[zero].
Note: Duplicate are acceptable.
Note: FirstOrDefault returns if matchs the element returns the matched element.
So every Extension has Specific meaning.
No comments:
Post a Comment