Reputation: 93
I've have the following code example from Microsoft (http://msdn.microsoft.com/en-us/library/bb534869.aspx):
String[] fruits = {"apple", "banana", "mango", "orange", "passionfruit", "grape" };
var query = fruits.Select((fruit, index)
=> new {Substring = fruit.Substring(0, index)});
foreach (var obj in query)
Console.WriteLine("{0}", obj);
This works quite well, but what I m not understand is what type of query is?
I ve tried to get out the info from the debugger but i was not able to declare it and write it down explicitly. I ve tried several variants e.g.
IEnumerable<int,string> query = fruits.Select((fruit, index)
=> new {Substring = fruit.Substring(0, index)});
but this does build at all. How can I define the query type explicit without using var?
Upvotes: 1
Views: 94
Reputation: 136239
Just for completeness, if you really must specify the type (and there really is no need to - an anonymous type is just as type-safe) then you must first declare a class/struct
public class FruitySubstringyThingy
{
public string Substring{get;set;}
}
and use that in the projection
IEnumerable<FruitySubstringyThingy> items
= fruits.Select((fruit,index) => new FruitySubstringyThingy{Substring = fruit.Substring(0, index)});
Upvotes: 1
Reputation: 721
When you use the new operator without a specific type, then the compiler creates an anonymous type that you can't refer to explicitly. If you want to be able to refer to it, then you should either create your own class to return explicitly, or return a pre-existing class. Try:
IEnumerable<string> query = fruits.Select((fruit, index) => fruit.Substring(0, index));
Upvotes: 2
Reputation: 16475
You cannot specify type because it is anonymous
. Read more here:
http://msdn.microsoft.com/en-us/library/bb397696.aspx
Upvotes: 7