c# - Lambda 表达式作为函数参数

标签 c#

我有以下代码

List<int> GetIndices<T>(List<T> list, ?????? condition
{
    var result =
            list
                .Select((p, index) => index)
                .Where(condition);

    return result.ToList();
}

我想这样调用它 GetIndices(someList, (p, index) => (someList[index].Height < someList[index - 1].Height))

condition 的正确类型是什么? ?

最佳答案

您的代码中有一个错误:Where期望一个返回 bool 的委托(delegate)值并将列表元素类型作为输入。

var result = list
   .Select((p, index) => index) // projects the element to it's index (of type int)
   .Where(condition);           // => expects Func<int, bool>

所以你需要 Func<int,bool>

但是,根据您的规范,我认为您想要 Func<T,int,bool> ,这意味着您必须重写 GetIndices 的实现作为

var result = list
   .Select((p, index) => new {p, index}) 
   .Where(x => condition(x.p, x.index))
   .Select(x => x.index);  

关于c# - Lambda 表达式作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5965985/

相关文章:

javascript - 将 List<KeyValuePair<string,string>> 传递给 WebAPI 会得到空值

c# - 如何在 Linux 上的 C# 中安全地将字节数组转换为字符串(在单声道下)?

c# - 从控制台应用程序隐藏控制台窗口

c# - 根据值更改 DataGridView 列的颜色

c# - 当它绑定(bind)到 XmlDataProvider 时,如何在 WPF DataGrid 中创建一个新行?

c# - 绑定(bind)到一列数据网格并应用样式

c# - 如何检查列表中具有唯一组合的多个属性,其中属性名称可作为单独的集合使用。 [C#]

c# - Await 运算符只能在 Async 方法中使用

C# WPF 加密

c# - 反 XSS 库删除 UL 标签。为什么?