Please navigate to the bottom of the page for Table of Contents

Saturday, July 28, 2012

LINQ interview questions part 3

In this post, we will do a quick review of LINQ operators Any() and All().

Question 1: Using LINQ, determine if any word in a list contains the substring “ei”.

 
    string[] words = { "believe", "relief", "receipt", "field" };
    bool iAfterE = words.Any(w => w.Contains("ei"));
    Console.WriteLine("list has words that contains 'ei': {0}", iAfterE);


Question 2: Using LINQ, return a grouped list of products only for categories that have at least one product that is out of stock.


In this case, we run any over a grouping as shown below:



 
    List<Product> products = GetProductList();
    var productGroups =
        from p in products
        group p by p.Category into g
        where g.Any(p => p.UnitsInStock == 0)
        select new { Category = g.Key, Products = g };

Question 3: Determine if an array of numbers contains all odds.



int[] numbers = { 1, 11, 3, 19, 41, 65, 19 };
bool onlyOdd = numbers.All(n => n % 2 == 1);
Console.WriteLine("The list contains only odd numbers: {0}", onlyOdd);

Question 4: Using LINQ, return a grouped list of products only for categories that have all of their products in stock.



 
    List<Product> products = GetProductList();
 
    var productGroups =
        from p in products
        group p by p.Category into g
        where g.All(p => p.UnitsInStock > 0)
        select new { Category = g.Key, Products = g };
    

8 comments:

  1. good article
    sanjay gupta

    ReplyDelete
  2. Very good... thanks.

    More please!

    ReplyDelete
  3. Extremely hard to reveal these helpful page or site. I have numerous gadgets and accomplishing legitimate article of these worked admirably and vitality keeps on being seeing about this web blog. You can use this assignment writing service for any kind of essay writing work.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Thanks for the great post! Your QAs have been added to the www.fullstack.cafe portal and back-linked!

    ReplyDelete