首页 > 解决方案 > C# Linq Lamba 元素计数

问题描述

我对 LINQ 有一个问题,我不知道如何解决在某些条件下计算元素的问题。

解释:

我在类型的对象中有以下一组元素List<Dispositivo> _devices

{
    root: [{
            dispositivo: 413,
            variables: [{
                    name: "Ignition",
                    value: false,
                    type: "Boolean",
                    unit: "boolean",
                    utc: "2021-05-06T21:06:36.0000000Z"
                }, {
                    name: "Speed",
                    value: 0,
                    type: "Double",
                    unit: "M/S",
                    utc: "2021-05-06T21:06:54.0000000Z"
                }
            ]
        }, {
            dispositivo: 418,
            variables: [{
                    name: "Ignition",
                    value: true,
                    type: "Boolean",
                    unit: "boolean",
                    utc: "2021-05-06T21:08:19.0000000Z"
                }, {
                    name: "Speed",
                    value: 19.3888888888889,
                    type: "Double",
                    unit: "M/S",
                    utc: "2021-05-06T21:08:19.0000000Z"
                }
            ]
        }, {
            dispositivo: 419,
            variables: [{
                    name: "Ignition",
                    value: true,
                    type: "Boolean",
                    unit: "boolean",
                    utc: "2021-03-22T20:20:22.0000000Z"
                },{
                    name: "Speed",
                    value: 0,
                    type: "Double",
                    unit: "M/S",
                    utc: "2021-05-04T16:19:06.0000000Z"
                }
            ]
        }
    ]
}

课程:

class Variables 
{
    string name,
    object value,
    type    string,
    unit    string,
    utc     string
}

class Dispositivos
{
    int device ,
    Lis<Variables> variables 
}

我编写了以下代码来尝试在以下条件下计算 this 的变量:

统计“Ignition”变量设置为“true”且“Speed”变量大于等于 5 的设备。

我写了这个,但它对我不起作用,它给了我版本中的错误。

var sobrevelocidad = _devices.Count(d => d.variables.Where(s => s.name == "Speed" && s.value.ToString() == "true"));

在此处输入图像描述

如果有人在 LINQ 和 LAMBDA 上胜过更多,你可以帮我一把。

非常感谢大家。

标签: c#linqlambda

解决方案


问题是 Count 方法需要一个返回布尔值的 lambda 表达式。

例如:

var sobrevelocidad = _devices.Count(d => 
    d.variables.Any(s => s.name == "Speed" && s.value >= 5) &&
    d.variables.Any(s => s.name == "Ignition" && s.value.ToString() == "true")
);

推荐阅读