How can you pre-define a variable that will contain an anonymous type?

Posted by HitLikeAHammer on Stack Overflow See other posts from Stack Overflow or by HitLikeAHammer
Published on 2011-03-09T17:39:52Z Indexed on 2011/03/10 16:10 UTC
Read the original article Hit count: 270

Filed under:
|

In the simplified example below I want to define result before it is assinged. The linq queries below return lists of anonymous types. result will come out of the linq queries as an IEnumerable<'a> but I can't define it that way at the top of the method. Is what I am trying to do possible (in .NET 4)?

            bool large = true;
            var result = new IEnumerable();   //This is wrong

            List<int> numbers = new int[]{1,2,3,4,5,6,7,8,9,10}.ToList<int>();

            if (large)
            {
                result = from n in numbers
                             where n > 5
                             select new
                             {
                                 value = n
                             };
            }
            else
            {
                result = from n in numbers
                             where n < 5
                             select new
                             {
                                 value = n
                             };
            }

            foreach (var num in result)
            {
                Console.WriteLine(num.value);
            }

EDIT: To be clear I know that I do not need anonymous types in the example above. It is just to illustrate my question with a small, simple example.

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about c#-4.0