【问题标题】:how to check how many times an item exists in list in c#? [duplicate]如何检查一个项目在c#中的列表中存在多少次? [复制]
【发布时间】:2021-01-26 01:08:35
【问题描述】:

你知道如何检查一个项目在 c# 列表中存在多少次吗?我试过了

    List<int> numbers = new List<int>();
    numbers.Add(1);
    numbers.Add(1);
    numbers.Add(2);
    numbers.Add(2);
    Console.WriteLine(numbers.Count);

但它是列表中的项目数(4 个项目),但我希望有两个“1”和两个“2”。你知道怎么做吗?请帮帮我。

【问题讨论】:

标签: c# .net


【解决方案1】:

您可以创建一个分组,然后使用 LINQ 从中创建一个字典:

Dictionary<int, int> numberFrequency = numbers
    .GroupBy(n => n)
    .ToDictionary(g => g.Key, g => g.Count());

然后要找出 4 出现了多少次,您可以这样检查:

int toFind = 4;
if (!numberFrequency.TryGetValue(toFind, out int frequency))
{
    frequency = 0;
}
Console.WriteLine($"{toFind} occurred {frequency} time(s).");

或者你可以循环遍历:

foreach (KeyValuePair<int, int> kv in numberFrequency)
{
    Console.WriteLine($"{kv.Key} occurred {kv.Value} time(s).");
}

Docs for GroupBy

Docs for ToDictionary

您可能还需要OrderByOrderByDescending


Try it online

【讨论】:

  • 谢谢我会试试这个
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 2022-11-12
  • 2019-07-26
  • 1970-01-01
  • 2022-08-24
  • 1970-01-01
相关资源
最近更新 更多