c# - 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 上胜过更多,你可以帮我一把。
非常感谢大家。
解决方案
问题是 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")
);
推荐阅读
- paypal - Paypal API v2 请求不记名令牌
- apache-spark - Spark UDF 使用 Cassandra 连接器查找密钥
- html - 如何在横幅图像中垂直居中页面标题文本(无弹性框/网格)?
- laravel - 如何将列类型从整数更改为大整数,而其他表在 laravel 中具有外部 id 关系?
- android - 具有多种风格的android签名应用程序的问题
- dialogflow-es - 当我在制作后不断删除代理时,我们可以在对话流中制作多少个代理
- python - 带有模块的用户 ironpython
- javascript - Google Maps Javascript API 在 JS Fiddle 中工作但未显示在 localhost
- google-apps-script - 有没有办法将 Google 幻灯片中的脚本链接到对象?
- python - 如何直接将代码应用于a中的所有文件并将xml文件转换为txt文件