Friday, 9 March 2012

How to use Any() and All() Extension with all Overloads?

Yes, we have Any() Extension method which is used to check for our collection/array contains any element it checks

Any()-àChecks for at least one Element.

Ex:
                        Int[] intarr=new int[4];
            intarr1[0] = 150;
            intarr1[1] = 80;
            intarr1[2] = 80;
            intarr1[3] = 150;
            intarr1[4] = 14;

Even  any element is not store it will store zero so no error by runtime.

Now overloads:

 Any(conditation);-àChecks for at least matching conditation

Conditation—I s equals like x => x == 140----false;

Conditation—I s equals like x => x == 14----true;

All() method one method
public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource,bool> predicate);
Ex:

          int[] intarr1 = new int[4];
            intarr1[0] = 80;
            intarr1[1] = 80;
            intarr1[2] = 80;
            intarr1[3] = 80;        
              
             int m=Convert.ToInt32(Console.ReadLine());
             bool b1 = intarr1.All<int>(x => x == m);   
             Console.WriteLine(b1);

If passing value not matches in the one of the value didn’t match returns false.As well as on of the value in the intarr1 contain different then passing value also returns false.

Like intarr1[3]=81;  // false

Take (how many elements we want):

Take() Return type IEnumerable<T>

         int[] intarr1 = new int[4];
            intarr1[0] = 84;
            intarr1[1] = 83;
            intarr1[2] = 86;
            intarr1[3] = 80;
          IEnumerable<int>  x =intarr1.Take<int>(4);
          IEnumerator<int> ier = x.GetEnumerator();
          while (ier.MoveNext())
          {
              int value = ier.Current;
              Console.WriteLine(value);         
          }                                 
          Console.Read();       
Note:IN EVERY EXTENSION THE CONDITION SHOULD BE LIKE OF lamda expression
            int[] intarr1 = new int[4];
            intarr1[0] = 84;
            intarr1[1] = 83;
            intarr1[2] = 86;
            intarr1[3] = 80;
            int value1 = Convert.ToInt32(Console.ReadLine());
            int value2 =  Convert.ToInt32(Console.ReadLine());
            IEnumerable<int> x = intarr1.TakeWhile<int>(value =>value1 == value2);
          IEnumerator<int> ier = x.GetEnumerator();
          while (ier.MoveNext())
          {
              int value = ier.Current;
              Console.WriteLine(value);         
          }Console.Read();

Value1 is equal to Value2 to satifiy the condition of lamda expression

No comments:

Post a Comment