1
int[] array = new int[10];
array[0] = 1;
array[1] = 1;
array[2] = 1;
array[3] = 2;
array[4] = 1;
array[5] = 2;
array[6] = 1;
array[7] = 1;
array[8] = 2;
array[9] = 3;

我想得到这个结果:

1 => 6 times
2 => 3 times
3 => 1 times

有没有什么简单的方法可以得到这个结果if-else statement

谢谢。

4

6 回答 6

9

是的,通过使用 LINQ 的GroupBy()

var res = array.GroupBy(x => x)
               .Select(x => new {Number=x.Key,Times=x.Count()})
               .ToList();

注意:
ToList()如果您只想迭代结果一次,则可能没有必要。

于 2012-08-28T13:46:48.400 回答
2

您可以使用 LINQ 并对数据进行分组:

var result = array.GroupBy(x => x)
                  .Select(x => new { Value = x.Key, Count = x.Count() });
于 2012-08-28T13:46:59.050 回答
2
array.GroupBy(a => a).Select(a => new { Value = a.Key, Count = a.Count() });
于 2012-08-28T13:47:29.727 回答
1

This is a Linq statement that will allow you to build your output:

array.GroupBy(x => x).Select(x => new { x.Key, Count = x.Count() } );
于 2012-08-28T13:49:38.913 回答
1

Enumerable.GroupBy groups a sequence by a selector. Then you can use the groups to count them or do whatever you need.

var countGroups = array.GroupBy(a => a)
                       .OrderByDescending(g => g.Count());

foreach(var g in countGroups)
    Console.WriteLine("{0} => {1} times", g.Key, g.Count());

Here's a demo with your sample: http://ideone.com/WatNL

于 2012-08-28T13:49:45.313 回答
1

您可以使用 Linq 来计算结果。如果您将以下内容放在控制台应用程序中,它应该可以工作:

using System;
using System.Linq;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[10];
            array[0] = 1;
            array[1] = 1;
            array[2] = 1;
            array[3] = 2;
            array[4] = 1;
            array[5] = 2;
            array[6] = 1;
            array[7] = 1;
            array[8] = 2;
            array[9] = 3;

            var group = from i in array
                        group i by i into g
                        select new
                        {
                            g.Key,
                            Sum = g.Count()
                        };

            foreach (var g in group)
            {
                Console.WriteLine(g.Key + " " + g.Sum);
            }
        }
    }
}
于 2012-08-28T13:48:29.697 回答