This is a mirror of official site: http://jasper-net.blogspot.com/

LINQ interview questions

| Monday, July 30, 2012
In this post we will review a bunch of small and simple LINQ interview questions to get you started. Once you understand these standard query expressions, it should be a breeze for you to answer LINQ questions.

Question: Given an array of numbers, find if ALL numbers are a multiple of a provided number. For example, all of the following numbers - 30, 27, 15, 90, 99, 42, 75 are multiples of 3.

The trick here is to use the Enumerable.All<TSource> method which determines whether all elements of a sequence satisfy a condition.

static void Main(string[] args)
{
    int[] numbers = { 30, 27, 15, 90, 99, 42, 75 };

    bool isMultiple = MultipleTester(numbers, 3);
}

private static bool MultipleTester(int[] numbers, int divisor)
{
    bool isMultiple =
        numbers.All(number => number % divisor == 0);
    
    return isMultiple;
}

Question: Given an array of numbers, find if ANY of the number is divisible by 5. For example, one of the following numbers - 30, 27, 18, 92, 99, 42, 72 is divisible by 5. 

Again, the key fact here is to use Enumerable.Any<TSource> method which determines whether any element of a sequence satisfies a condition. The code is very similar to the ALL case. 

 

static void Main(string[] args)
{
    int[] numbers = { 30, 27, 18, 92, 99, 42, 72 };
        
    bool isDivisible = IsDivisible(numbers, 3);
}

private static bool IsDivisible(int[] numbers, int divisor)
{
    bool isDivisible =
        numbers.Any(number => number % divisor == 0);
    
    return isDivisible;
}

Another way to present a similar question that utilizes Enumerable.Any<TSource> method is shown below. 

Question: Given a GPSManufacturer and GPSDevice data structure as defined below, find all the manufacturers that have at least 1 or more active GPS devices. 

class GpsDevice
{
    public string Name;
    public bool IsActive;
}

QR: Inline image 1 Inline image 2

Posted via email from Jasper-net

0 comments: