tags:

views:

645

answers:

4

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
}
+4  A: 

IQueryable http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx

So your method declaration would look like

public IQueryable GetSomeData()
Ryan Lanciaux
Thanks! That helps tremendously/
Scott
By doing this you won't have intellisense and can only access the properties of items through reflection.
Darren Kopp
Be aware that the query has not running yet.
Eduardo Molteni
Yes I just noticed this..I don't have intellisense. There must be a better way.
Scott
It depends on your definition of better way. Lazy loading is nice for many circumstances.
Ryan Lanciaux
+1  A: 

If you want to return, you need a type.

Instead of var, declare using IEnumerable<> and return that variable. Iterating through it actually executes the query.

Gulzar
+3  A: 

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
             };
Darren Kopp
THANK YOU so much for expanding on this solution. The key was using a specific type. This works great
Scott
Hey I gave that answer 1 hour befor Darren. Serves me right for not giving a sample:)
Gulzar
To be clear, what's happening is that select new {...} creates an anonymous type (requiring the use of var keyword). This type has no name and can only be used locally in the method that created it (unless you use reflection). To use it outside, you need to created a named type.
Lucas
+1  A: 

A generic method should give you intellisense:

public class MyType {Key{get;set;} Value{get;set}}

public IQueryable<T> GetSomeData<T>() where T : MyType, new() 
 { return from a in db.MyTable
          where a.MyValue == "A" 
          select new T {Key=a.Key,Value=a.MyValue};
 }
Mark Cidade