简体   繁体   中英

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#. 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)

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.

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.

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