Friday, 9 March 2012

How to use Single() Extension with all Overloads?

Yes, Single() is one extension method which has overloads also how to use these overloads
we will see now


Single Extensions:
public static TSource Single<TSource>(this IEnumerable<TSource> source);
public static TSource Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source);
public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);


Single :Returns the one and only occurrence

Ex:

int[] intarr2 = new int[1];
intarr2[0] = 150;
int i = intarr2.Single<int>();
Console.WriteLine(i);--à150

int[] intarr3 = new int[1];  // no value in the array even single returns zero
int i = intarr3.Single<int>();
Console.WriteLine(i);--à0 zero

SingleOrDefault<int>();

--------find value -àreturns value ex:150 same like single<int>();

which is also work for only size of array is 1 one only.

In Case of overloads

          int[] intarr4 = new int[5];
           intarr4[0] = 150;
           intarr4[1] = 80;
           intarr4[2] = 25;
           intarr4[3] = 15;
           intarr4[4] = 14;
            int i = intarr4.Single<int>(x=>x==80);
            Console.WriteLine(i);
            int j = intarr4.SingleOrDefault<int>(y => y == 74);
            Console.WriteLine(j);
            Console.Read();
Here i  is 80 in case of single conditation is matched so returns value of I is 80
if not match single<int>(x=>==80) returns error

Incase of SingleOrDefault<int>(y => y == 74); // no 74 in intarr4 array
Condatation is not matched but no error by because default value will returns
Conculsion: incase of
Single<int>()
   Or
SingleOrDefault<Tsource>();--àmenas no overloads requires size of array is 1 only.
Why because if it has more then size 1 it gives [runtime asking which single]error by runtime.So go for overloaded.

Incase of overloads:

intarr4.Single<int>(x=>x==80);---condition matchs returns the value.
Other wise error.

intarr2.SingleOrDefault<int>(y => y == 74);
condition matchs returns the value other wise no error Gives zero[default value).

No comments:

Post a Comment