I’m doing the following request. It works as supposed to and returns data structured correctly. (It creates an element with “head” corresponding to the common field and puts the all elements of the same value in that field as a an Array in the “tail”.)
var result
= from A in As
group A by A.F into B
select new
{
F1 = B.Key,
F2 = from A in As
where A.F == B.Key
select A
};
Now I’d like to declare it’s type explicitly. I’ve checked in the debugger that my assumption on types is correct, however, when I try to declare that, it gives me conversion errors.
- Why?
- How can I declare the type explicitly?
I’ve tried different variant of declarations and as but failed.
IEnumerable<Tuple<String, IEnumerable<MyType>>> result
= from ...
} as Tuple<String, MyType>;
I know it’s doable but I lack the experience to get it right. I’ve noticed that the following works. However, I’m not sure how to take it a step further, exchanging Object for the actual variable type.
IEnumerable<Object> result
= from ...
} as Object;
Although you know that the object “insides” are the same, C# is statically typed and resolves types based on their metadata (name, namespace…), not on their members. You select an anonymous type, not a
Tuple, so the type resolver cannot “agree” with it being used as aTuple.If you hover over the
varkeyword in Visual Studio, it will tell you what type is it (because it must be known during compile time, unless it’s adynamic). However due to the fact you are using anonymous type, you will not be able to write the type explicitly – it has no name in the C# source code.What you might do is either define the type elsewhere
and then use it in your query:
or use a
Tupleas Jon suggested here.