Possible Duplicate:
LINQ to SQL: Return anonymous type?
This is my code:
class B
{
public int age { get; set; }
public string name { get; set; }
}
class Program
{
static List<whatshouldIwritehere> GetList()
{
List<B> list = new List<B>() {
new B(){ age = 10, name = "jaagu" },
new B(){ age = 20, name = "juggu" },
new B(){ age = 30, name = "jockey" },
new B(){ age = 40, name = "jaggu" },
};
return (from item in list
select new { MyAge = item.age, MyName = item.name }).ToList();
}
static void Main(string[] args)
{
Console.Read();
}
}
Can anybody tell me what should I write in the return type of function GetList()? I know the query creates a anonymous class and I want to work with that class across functions. If I create a custom class with MyAge and MyName then it’s very easy to give that in return type. However, is there any other way out ? Had this been in same function I would have used var keyword. But I can’t use that here.
You can return
List<object>orList<dynamic>.If you return
objectthen you won’t be able to access the properties except with reflection.If you return dynamic then you can access the properties, but you lose the compile time check. (So a typo with in property name will result in a runtime exception).
EDIT:
You need to specify the type explicitely for the ToList function: