首页 > 解决方案 > 计算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)*

标签: c#listlinq

解决方案


尝试GroupByLinq),例如:

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;

推荐阅读