Basically, I want to be able to create an Object and pass in a LINQ query to it as a property and store that property...
I know I could always just run the LINQ query in the code that wants to filter a collection, but I thought it'd be interesting if my Object could retain that query so that other classes that reference it ca开发者_高级运维n grab that query...
Pseudo-Code
public class MyClass
{
public MyClass(?? linq)
{
TheLinq = linq;
}
public ?? TheLinq { get; set; }
}
It sounds like you want something very close to the following:
public class Program {
private static void Main(string[] args) {
Func<List<string>, IEnumerable> testQuery = x => x.Where<IEnumerable>(y => !y.Equals("Yucky"));
var testArray=new string[] {"Hello", "Yucky", " ", "World"};
var testClass=new MyClass(testQuery);
var resultStrings = testClass.query(testArray.ToList());
// Printing resultStrings should result in "Hello World"
foreach (string s in resultStrings) {
Console.Write(s);
}
}
}
public class MyClass {
public Func<List<string>, IEnumerable> query { get; private set; }
public MyClass(Func<List<string>, IEnumerable> aQuery)
{
query=aQuery;
}
}
EDIT: Checked, and yes this does work
In general, you will need to tailor the Func<input, output>
as you would like it to end up, but this should work perfectly well for you, I should think!
And just for a little bit of read-ability, the func here could be rewritten with less ambiguous variable names like: Func<List<string>, IEnumerable> testQuery = theListToQuery => theListToQuery.Where<IEnumerable>(stringInList => !stringInList.Equals("Yucky"));
If you are looking to retain the query expression and manipulate it, consider the following:
public class MyClass
{
public MyClass(IQueryable<MyClass> linq)
{
TheLinq = linq;
}
public IQueryable<MyClass> TheLinq { get; set; }
}
I think you are looking to use Expression Trees. The Expression objects (expr and expr1) are instances of the type you are trying to explain above. These expression objects can be passed around and compiled as necessary:
List<int> ints = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9};
Expression<Func<IEnumerable<int>, IEnumerable<int>>> expr = x=> x.Where(y=> y>6);
Expression<Func<IEnumerable<int>, IEnumerable<IGrouping<bool,int>>>> expr1 = x => x.GroupBy(y => y > 6);
// first expression
var bobs = expr.Compile()(ints);
foreach(var bob in bobs)
{
Console.WriteLine(bob);
}
// second expression
var bobs1 = expr1.Compile()(ints);
int counter = 0;
foreach (IGrouping<bool, int> bob in bobs1)
{
Console.WriteLine("group " + counter++ + " values :");
foreach (var t in bob)
{
Console.WriteLine(t);
}
}
精彩评论