I'm a very beginner of C# and have some troubles with correct understading of generic types. In this example I would like to somehow store a query result into a variable.
The code I showed below is incorrect, because generic type T should specified.
public class Data
{
public IQueryable<T> Results { get; set; }
public Data()
{
var db = new Database();
}
public void Store()
{
Results = db.Products.Select(x => new { x.ProductName, x.Cost });
}
}
Is it possible to do it without declaring a special class for only one use, like this one?
public class ProductView
{
public string ProductName { get; set; }
public int Country { get; set; }
}
...
public IQueryable<ProductView > Results { get; set; }
Also, why dynamic type doesn't suit in this example?
public dynamic Results { get; set; }
There are 3 ways to solve this problem:
1) Create class like
ProductViewthat you mentioned - classical C#6 or older way2) Use
dynamicinstead ofTlike:public IQueryable<dynamic> Results { get; set; }- not recommended, because it increases risk of runtime errors and reduces readability3) Use tuples (C#7 feature):