Linq直方图

时间:2011-01-05 05:14:15

标签: c# linq

有没有办法用linq进行分割的组织图?我已经看过几个例子,你可以计算特定对象的出现次数。是否有可能创建一个基于linq的历史图,它计算两个值之间一系列对象的出现次数?

我不知道如何按一系列项目分组来创建直方图所需的存储桶?假设使用起始边界和宽度来创建范围。

您需要遍历数字数组并将每个数字分组为是否为< = Upper Bound和>下界。然后你只需要对每个组进行求和。我不知道如何按部分完成小组

2 个答案:

答案 0 :(得分:3)

您可以执行以下操作:

var groups = input.GroupBy(x => (int)((x.value - start)/width));

为每个条形和组创建一个整数值。

答案 1 :(得分:3)

这样的东西?

        Random randF = new Random();
        List<double> nums = new List<double>();
        for (int i = 0; i < 100000; i++)
        {
            nums.Add(randF.NextDouble()*100);
        }

        double fromXF = 30;
        double toXF = 80;
        int groupCount = 10; // number of groups between values
        var histF = from i in nums
                    let groupKeyF = ((i-fromXF)/(toXF-fromXF)*groupCount) // even distribution of "groupCount" groups between fromXF and toXF, simple math, really
                    where groupKeyF >= 0 && groupKeyF < groupCount // only groups we want
                    let groupKey = (int)groupKeyF // clamp it to only group number
                    group i by groupKey into gr  // group it according to group number
                    orderby gr.Key
                    select new { Value = gr.Key, Count = gr.Count() };

        foreach (var item in histF)
        {
            Console.WriteLine("Group number: " + item.Value + ", Count: " + item.Count);
        }