Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return an anonymous type from a method?

I have a Linq query that I want to call from multiple places:

var myData = from a in db.MyTable
             where a.MyValue == "A"
             select new  {
                            a.Key,
                            a.MyValue
                          };

How can I create a method, put this code in it, and then call it?

public  ???  GetSomeData()
{
   // my Linq query
}
like image 459
ScottG Avatar asked Sep 10 '08 19:09

ScottG


2 Answers

IQueryable and IEnumerable both work. But you want to use a type specific version, IQueryable<T> or IEnumerable <T>.

So you'll want to create a type to keep the data.

var myData = from a in db.MyTable
             where a.MyValue == "A"
             select new MyType
             {
                 Key = a.Key,
                 Value = a.MyValue
             };
like image 118
Darren Kopp Avatar answered Oct 03 '22 02:10

Darren Kopp


IQueryable

So your method declaration would look like

public IQueryable GetSomeData()
like image 44
Ryan Lanciaux Avatar answered Oct 03 '22 03:10

Ryan Lanciaux