我在C#中有以下代码示例,演示了如何将一些LINQ查询解析为函数的参数.
public List<object> AllElements;
public object GetAll<T>(SomeLINQQuery) {
//get some elements from AllElements where the argument is added to the query, as shown below.
}
Run Code Online (Sandbox Code Playgroud)
现在,为了赋予这个意义,我想要实现的是:
public void test() {
GetAll<object>(where object.ToString() == "lala");
}
Run Code Online (Sandbox Code Playgroud)
这很难解释.我希望这个例子做得好.
Dan*_*rth 12
当然.你会这样做:
public List<T> GetAll<T>(List<T> list, Func<T, bool> where)
{
return list.Where(where).ToList();
}
Run Code Online (Sandbox Code Playgroud)
你会这样称呼它:
var result = GetAll(AllElements, o => o.ToString() == "lala");
Run Code Online (Sandbox Code Playgroud)
您甚至可以将其创建为扩展方法:
public static List<T> GetAll<T>(this List<T> list, Func<T, bool> where)
{
return list.Where(where).ToList();
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
var result = AllElements.GetAll(o => o.ToString() == "lala");
Run Code Online (Sandbox Code Playgroud)
但实际上,在您的简单示例中,它没有任何意义,因为它与Where直接使用完全相同:
var result = AllElements.Where(o => o.ToString() == "lala").ToList();
Run Code Online (Sandbox Code Playgroud)
但是,如果你的GetAll方法做了更多的东西,那么将谓词传递给该方法是有意义的.
| 归档时间: |
|
| 查看次数: |
6593 次 |
| 最近记录: |