LINQ组按序列和计数进行排序

时间:2013-10-23 20:04:15

标签: c# linq count linq-group

我正在寻找一种最佳性能方法,使用LINQ对序列进行分组和计数。我将处理甚至超过500 MB的文件,因此性能是该任务中最重要的关键。

List<int[]> num2 = new List<int[]>();
num2.Add(new int[] { 35, 44 });
num2.Add(new int[] { 200, 22 });
num2.Add(new int[] { 35, 33 });
num2.Add(new int[] { 35, 44 });
num2.Add(new int[] { 3967, 11 });
num2.Add(new int[] { 200, 22 });
num2.Add(new int[] { 200, 2 });

结果必须是这样的:

[35,   44]  => 2
[200,  22] => 2
[35,   33] => 1
[35,   44] => 1
[3967, 11] => 1
[200,  2 ] => 1

我做过这样的事情:

        Dictionary<int[], int> result2 = (from i in num2
                                       group i by i into g
                                       orderby g.Count() descending
                                       select new { Key = g.Key, Freq = g.Count() })
                          .ToDictionary(x => x.Key, x => x.Freq);

        SetRichTextBox("\n\n Second grouping\n");

        foreach (var i in result2)
        {
            SetRichTextBox("\nKey: ");
            foreach (var r in i.Key)
            {
                SetRichTextBox(r.ToString() + "  ");
            }

            SetRichTextBox("\n  Value: " + i.Value.ToString());

        }

但它无法正常工作。有帮助吗?

2 个答案:

答案 0 :(得分:1)

对于长度为2的数组,这将有效。

num2.GroupBy(a => a[0])
    .Select(g => new { A0 = g.Key, A1 = g.GroupBy(a => a[1]) })
    .SelectMany(a => a.A1.Select(a1 => new { Pair = new int[] { a.A0, a1.Key }, Count = a1.Count() }));

我认为应该给你最佳表现;您也可以在第一个Select语句后尝试.AsParallel()子句。

此策略(按数组的第n个元素连续分组)通用于任意长度的数组:

var dim = 2;

var tuples = num2.GroupBy(a => a[0])
    .Select(g => new Tuple<int[], List<int[]>>(new [] { g.Count(), g.Key }, g.Select(a => a.Skip(1).ToArray()).ToList()));

for (int n = 1; n < dim; n++)
{
    tuples = tuples.SelectMany(t => t.Item2.GroupBy(list => list[0])
        .Select(g => new Tuple<int[], List<int[]>>(new[] { g.Count() }.Concat(t.Item1.Skip(1)).Concat(new [] { g.Key }).ToArray(), g.Select(a => a.Skip(1).ToArray()).ToList())));
}

var output = tuples.Select(t => new { Arr = string.Join(",", t.Item1.Skip(1)), Count = t.Item1[0] })
    .OrderByDescending(o => o.Count)
    .ToList();

生成

的输出
Arr = "35, 44", Count = 2
Arr = "200, 22", Count = 2
Arr = "35, 33", Count = 1
Arr = "200, 2", Count = 1
Arr = "3967, 11", Count = 1
在你的例子中

。我会让你测试更高的尺寸。 :)

您应该能够在没有太多困难的情况下并行化这些查询,因为连续的分组是独立的。

答案 1 :(得分:0)

您可以这样做:

var results = from x in nums
              group x by new { a = x[0], b = x[1] } into g
              orderby g.Count() descending
              select new
              {
                  Key = g.Key,
                  Count = g.Count()
              };

foreach (var result in results)
    Console.WriteLine(String.Format("[{0},{1}]=>{2}", result.Key.a, result.Key.b, result.Count));

诀窍是想出一种方法来比较数组中的值,而不是数组本身。

备选(可能更好的选项)是将您的数据从int[]转换为某种自定义类型,覆盖该自定义类型上的相等运算符,然后仅group x by x into g,但如果您是真的坚持int[]然后这个工作。

相关问题