Monday, September 10, 2012

LINQ Query, Selection, Partial Selections and Aggregations


LINQ allows you to write structured, type-safe queries over local object collections and remote data sources. LINQ interview questions are short and allow the interviewer to quickly test the depth of your knowledge in LINQ and to a certain degree, extension methods.
Let’s review a bunch of small functions that show you a few LINQ operations.
The example below shows you how to use the Where and Select LINQ extensions:

public static void LinqQueryAndSelection()
{
    List<string> fruits = new List<string> 
                    { "apple", "passionfruit", "banana", "mango", 
                      "orange", "blueberry", "grape", "strawberry" };
        
    // find all fruits that have names of length 5 or less
    IEnumerable<string> query1 = fruits.Where(fruit => fruit.Length < 6);
        
    foreach (string fruit in query1)
        Console.WriteLine(fruit);
        
    // convert the names of all the fruits to uppercase
    IEnumerable<string> query2 = fruits.Select(n => n.ToUpper());
        
    foreach (string fruit in query2)
        Console.WriteLine(fruit);
}

This next example shows you how to do partial selections:

public static void LinqPartialSelection()
{
    List<string> fruits = new List<string> 
                    { "apple", "passionfruit", "banana", "mango", 
                      "orange", "blueberry", "grape", "strawberry" };
        
    // find first 3 fruits
    IEnumerable<string> query1 = fruits.Take(3);
        
    foreach (string fruit in query1)
        Console.WriteLine(fruit);
        
    // skip the first 3 fruits
    IEnumerable<string> query2 = fruits.Skip(3);
        
    foreach (string fruit in query2)
        Console.WriteLine(fruit);
        
    // single element operations
    string firstFruit = fruits.First(); // apple
    string lastFruit = fruits.Last(); //  strawberry
    string thirdFruit = fruits.ElementAt(2); // banana
    string fruitStratingWithM = fruits.First(f => f.StartsWith("m")); // mango
}

This last example shows you how to use LINQ to aggregate values:

public static void LinqAggregation()
{
    int[] numbers = { 3, 4, 5, 6, 7, 8 };
        
    // aggregation operations
    int count = numbers.Count(); // 6
    int min = numbers.Min(); // 3
    int max = numbers.Max(); // 8
    double average = numbers.Average(); // 5.5
        
    // the operators above also take an optional predicate
    int countEvensOnly = numbers.Count(n => n % 2 == 0);
        
    // assume that values decay over period
    // MAX and MIN functions allow the numbers to be transformed
    // before the operation
    int maxAfterMultiplicationByTwo = numbers.Max(n => n * 2); // 16
}

There is much more to LINQ than these starter examples. From an interviewing perspective you should learn in depth about the standard Query operations which can be broken down into several categories:
  • Filtering operations: Where, Take, Skip, etc. 
  • Project operations: Select, Join, etc. 
  • Ordering operations: OrderBy, ThenBy, Reverse. etc. 
  • Grouping operations: GroupBy 
  • Set operations: Concat, Union, etc. 
  • Element operations: First, FirstOrDefault, Last, etc. 
  • Aggregation operations: Count, Min, Max, Sum, etc. 
  • Qualifier operations: Contains, Any, All, etc. 
  • Conversion operations: ToArray, ToList, Cast, etc.
Another important fact to note is that LINQ operations can be chained as shown in the example below.

public static void LinqChaining()
{
    List<string> fruits = new List<string> 
                    { "apple", "passionfruit", "banana", "mango", 
                      "orange", "blueberry", "grape", "strawberry" };
        
    // operator chaining
    IEnumerable<string> query1 = fruits
                            .Where(f => f.Contains("a"))
                            .OrderBy(f => f.Length)
                            .Select(f => f.ToUpper());
        
    foreach (string fruit in query1)
        Console.WriteLine(fruit);
}

No comments:

Post a Comment