Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
257 views
Welcome To Ask or Share your Answers For Others

1 Answer

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...