public List<String> listStr = new listStr();
public List<String> FindString(Expression<Func<String, bool>> predicate)
{
// return a list that satisfies the predicate
}我正在试着做一个例子来理解如何在c#中使用表达式。你能帮我完成这段代码吗?
发布于 2011-12-20 23:07:16
像这样的东西?
public List<String> FindString(List<String> list, Func<String, bool> predicate)
{
return list.Where(predicate).ToList();
}为什么要使用表达式?如果你想使用它,那么你需要在之前编译它,但是除非你想在你的方法中对表达式进行一些操作,否则我建议使用上面的方法(或者直接使用linq的.Where()扩展方法)。
public List<String> FindString(List<String> list, Expression<Func<String, bool>> predicate)
{
var lambda = predicate.Compile();
return list.Where(lambda).ToList();
}发布于 2011-12-20 23:07:22
public List<String> FindString(Expression<Func<String, bool>> predicate)
{
return listStr.Where(predicate.Compile()).ToList();
}发布于 2011-12-20 23:09:22
public List<String> listStr = new List<String>();
public List<String> FindString(Expression<Func<String, bool>> predicate)
{
// return a list that satisfies the predicate
Func<string, bool> p = predicate.Compile();
return listStr.Where(p).ToList();
}附言:您的变量声明错误。
https://stackoverflow.com/questions/8577416
复制相似问题