Storing query result into a variable

415 Views Asked by At

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; }
2

There are 2 best solutions below

0
ingvar On

There are 3 ways to solve this problem:

1) Create class like ProductView that you mentioned - classical C#6 or older way

2) Use dynamic instead of T like: public IQueryable<dynamic> Results { get; set; } - not recommended, because it increases risk of runtime errors and reduces readability

3) Use tuples (C#7 feature):

public IQueryable<(string, int)> Results { get; set; } // I suppose ProductName is string and Cost is int

public void Store()
{
    Results = db.Products.Select(x => (x.ProductName, x.Cost));
}
0
Daniel Earwicker On

The problem here is that your Data class appears to know some specific things about T. In the Store method it reads the Products and obtains two specific properties from each item. So it is not actually a generic class that can store any type. It's very specific.

To make it generic you would need to remove the Store method. And then there is not much left. You need to decide what the purpose of Data is. What problem does it exist to solve?