c# - 计算c#列表中元素的实例
问题描述
我想知道如何处理列表中第一个元素Count
的实例,然后是第二个等,并输出这些值。
var SPFK_List = new List<string>() {
"one", "one", "one",
"two", "two",
"three", "three", "three"
};
Inputs.ones.Value = *(number of one's)*
Inputs.twos.Value = *(number of two's)*
解决方案
尝试GroupBy
(Linq),例如:
using System.Linq;
...
var SPFK_List = new List<string>() {
"one", "one", "one",
"two", "two",
"three", "three", "three"
};
// {3, 2, 3}
int[] counts = SPFK_List
.GroupBy(item => item)
.Select(group => group.Count())
.ToArray();
或者(Where
如果您只想计算某些项目,请添加)
// {{"one", 3}, {"two", 2}, {"three", 3}}
Dictionary<string, int> counts = SPFK_List
//.Where(item => item == "one" || item == "two")
.GroupBy(item => item)
.ToDictionary(group => group.Key, group => group.Count());
Inputs.ones.Value = counts.TryGetValue("one", out int count) ? count : 0;
推荐阅读
- json - Angular >= 2:从 JSON 读取 nan/undefined/infinity 的方法是什么?
- python - 如何在 django 中使用 ajax 形式验证 django-recaptcha
- python - Selenium 无法登录 Facebook
- node.js - 生成串行密钥 Node.js 重复问题
- haproxy - 使用 haproxy ssl 直通转发客户端 IP
- angular - 控制台中的角度材料 MatChipInputEvent 错误
- go - 使用自己的结构(解码的 JSON)初始化外部库结构会产生类型错误
- java - 正则表达式检测
...
代码块 - azure - Microsoft Azure - 允许特定 IP 访问特定页面
- python - 如何分别传递列表或元组的值并将它们保存为相应图像的属性