C# LINQ Teaser

Another great interview question.

Will the following code compile and if yes what will be the result of it ?

static void Main(string[] args)
{
    int[] array = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    Func<int, int> func = i => {
                          Console.Write(array[i]);
                          return i;
                     };

    var result = array.Where(e => e <= func(2)).ToArray ();
}
VN:F [1.9.3_1094]
Rating: 4.8/5 (9 votes cast)
C# LINQ Teaser, 4.8 out of 5 based on 9 ratings

  • DZone
  • Digg
  • Twitter
  • Yahoo Buzz
  • StumbleUpon
  • Delicious
  • Technorati Favorites
  • LiveJournal
  • Reddit
  • Share/Bookmark

A few posts you might find interesting:

  1. C# Byte Iteration Question
  2. C# Inheritance Question
  3. C# The “double” trouble
  4. C# Set method timeout using Generics
  5. C# Increment operator (++) question

  1. July 13th, 2009 at 01:07 | #1

    It will print the number 3 to stdout 10 times (so ‘*CORRECT ANSWER’), and result will be {1,2}. Tricky question though, easy to get it wrong and say ’12345678910′ :)

    VA:F [1.9.3_1094]
    Rating: 5.0/5 (1 vote cast)
  2. July 13th, 2009 at 09:43 | #2

    @Paul Betts
    This is what tricky question is supposed to do :)
    I’m replacing your CORRECT answer with “CORRECT ANSWER”, so others will have the opportunity to solve it on their own.

    VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
  3. July 14th, 2009 at 02:29 | #3

    I would simply refuse to answer on the basis that the code is not written using the best practice of writing easily understood code due to naming conventions used ;)

    Seriously, nice one. I had to read it like 10 times before I got the answer. Albeit I don’t specialize in the MS stack alone.

    VA:F [1.9.3_1094]
    Rating: 5.0/5 (1 vote cast)
  4. A
    August 29th, 2009 at 14:22 | #4

    Great Teaser.

    More, More…

    VA:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
  5. absurd
    April 7th, 2010 at 01:55 | #5

    Try this

    static void Main(string[] args)
    {
    int[] array = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    Func<int, int> func = i => {
    Console.Write(array[i]);
    return i;
    };

    var result = array.Where(e => e <= func(2));

    foreach (var w in result)
    Console.WriteLine(w);
    }

    VA:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
  1. No trackbacks yet.

Subscribe without commenting

SEO Powered by Platinum SEO from Techblissonline
watch free movies