Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

c# - Group by and count in List

I have an List which is filled with ints, like this:

[0] 1
[1] 4
[2] 4
[3] 8
[4] 9
[5] 1
[6] 1

So basically random numbers in there, but the same number can occure multiple times in that list.

What i want is to group them by number, but that i can also tell how many times that number was in the list. So that i have a something like:

[0] 
  [number] 1
  [total] 3  // Occured 3 times in the list
[1]
  [number] 4
  [total] 2
[2]
  [number] 8
  [total] 1
[3]
  [number] 9
  [total] 1

Is there a fast/easy way to accomplish this? Or do i have the write out all sorts of loops and checks to construct something like this manually?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use GroupBy and Count:

var numberGroups = numbers.GroupBy(i => i);
foreach(var grp in numberGroups)
{
    var number = grp.Key;
    var total  = grp.Count();
}

Here's another example which uses an anonymous type to store some informations. It also creates an array since it seems to be the desired result:

var numberGroups = numbers.GroupBy(i => i)
                   .Select(grp => new{
                       number  = grp.Key,
                       total   = grp.Count(),
                       average = grp.Average(),
                       minimum = grp.Min(),
                       maximum = grp.Max()
                   })
                   .ToArray();

foreach (var numInfo in numberGroups)
{
    var number = numInfo.number;
    // ...
    var maximum = numInfo.maximum;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...