如何显示数组元素出现多少次 [英] How to display how many times an array element appears

查看:131
本文介绍了如何显示数组元素出现多少次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C#,希望我能得到这个话题一定的帮助。我有一个元素的数组,我需要显示每一个项目出现多少次。

I am new to C# and hope I can get some help on this topic. I have an array with elements and I need to display how many times every item appears.

例如, [1,2,3,4,4,4,3] 1 出现一次, 4 出现了三次,依此类推。

For instance, in [1, 2, 3, 4, 4, 4, 3], 1 appears one time, 4 appears three times, and so on.

我做了以下但不`吨知道如何把它在foreach / if语句...

I have done the following but don`t know how to put it in the foreach/if statement...

int[] List = new int[]{1,2,3,4,5,4,4,3};
foreach(int d in List)
{
    if("here I want to check for the elements")
}

谢谢你,对不起,如果这是一个非常基本一...

Thanks you, and sorry if this is a very basic one...

推荐答案

您可以处理这种通过枚举。 GROUPBY 。我建议在看 C#LINQ样品的计数和GROUPBY部分的指导。

You can handle this via Enumerable.GroupBy. I recommend looking at the C# LINQ samples section on Count and GroupBy for guidance.

在你的情况,这可能是:

In your case, this can be:

int[] values = new []{1,2,3,4,5,4,4,3};

var groups = values.GroupBy(v => v);
foreach(var group in groups)
    Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());

这篇关于如何显示数组元素出现多少次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆