基本上,我希望能够创建一个对象并将 LINQ 查询作为属性传递给它并存储该属性...
我知道我总是可以在想要过滤集合的代码中运行 LINQ 查询,但我认为如果我的对象可以保留该查询以便引用它的其他类可以获取该查询,那将会很有趣。 ..
伪代码
public class MyClass
{
public MyClass(?? linq)
{
TheLinq = linq;
}
public ?? TheLinq { get; set; }
}
最佳答案
听起来您想要的东西非常接近于以下内容:
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;
}
}
编辑:已检查,是的,这确实有效
一般来说,您需要定制 Func<input, output>
正如您希望的那样结束,但我认为这对您来说应该非常适合!
为了提高可读性,这里的 func 可以用更明确的变量名重写,例如:Func<List<string>, IEnumerable> testQuery = theListToQuery => theListToQuery.Where<IEnumerable>(stringInList => !stringInList.Equals("Yucky"));
关于c# - 有什么方法可以将 LINQ 表达式存储为属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7674835/