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
}
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
};
IQueryable
So your method declaration would look like
public IQueryable GetSomeData()
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};
}
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.