简体   繁体   English

计算列表中所有元素的表达式

[英]evaluate an expression on all the elements of a list

public List<String> listStr = new listStr();

public List<String> FindString(Expression<Func<String, bool>> predicate)
{
// return a list that satisfies the predicate
}

I'm trying to make an example to understand how to use Expression in c#. 我正在尝试举一个例子来了解如何在c#中使用Expression。 Can you help me to complete this code? 您能帮我完成此代码吗?

Something like this? 像这样吗

public List<String> FindString(List<String> list, Func<String, bool> predicate)
{
    return list.Where(predicate).ToList();
}

Why do you use an expression?, if you want to use it then you need to compile it before, but unless you want to do some manipulation of the expression in your method I'd advise using the above (or directly using linq's .Where() extension method) 为什么要使用表达式?如果要使用它,则需要先对其进行编译,但是除非您想对方法中的表达式进行某些操作,否则建议您使用上面的表达式(或直接使用linq的.Where()扩展方法)

public List<String> FindString(List<String> list, Expression<Func<String, bool>> predicate)
{
    var lambda = predicate.Compile();
    return list.Where(lambda).ToList();
}
public List<String> FindString(Expression<Func<String, bool>> predicate)
{
  return listStr.Where(predicate.Compile()).ToList();
}
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();
}

PS: your variable declaration is wrong. PS:您的变量声明错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM