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
};
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.