Range division in c#

前端 未结 2 1690
执笔经年
执笔经年 2021-01-29 09:51

divide range values into groups, for example if the range between 0 and 100 and i have four groups A,B,C,D. if i want to divide the range into four groups like 0-25 group D 26

相关标签:
2条回答
  • 2021-01-29 10:00

    Here is some more sample code to help you out:

    var groups = new[] { "A", "B", "C", "D" };
    
    //Range size and group size is configurable, should work with any range.
    var range = Enumerable.Range(0, 1000).ToArray();
    var groupSize = range.Length / groups.Length;
    
    // Here we split range in groups. If range size is not exactly divisible
    // to groups size, all left elements go to the last group, then we form
    // a dictionary with labels as keys and array of numbers as values
    var split = range
        .GroupBy(c => Math.Min(c / groupSize, groups.Length - 1))
        .ToDictionary(c => groups[c.Key], c => c.ToArray());
    
    Console.WriteLine(String.Join(" ", ranges["A"]));   
    
    0 讨论(0)
  • 2021-01-29 10:08

    You could try something like:

        var someNumbers = new [] { 10,67,45,26,78,53,12,45,68};
        var groupNames = new [] { "A", "B", "C", "D" };
    
        //                               Key                      Value
        var result = someNumbers.GroupBy(v => groupNames[v / 25], p => p);
    
        foreach(var v in result.OrderBy(i => i.Key))
        {
            Console.WriteLine(v.Key);
            foreach(var k in v)
                Console.WriteLine("  " + k);
        }
    

    I group the values on value / 25 which will be an integer divide and group the values on portions of 25. For example: value 13. 13 / 25 = 0 so 13 will be grouped by 0. For example: value 67. 67 / 25 = 2, so it will be grouped by 2.

    The only problem is, that if the value exceeds 99, you get a IndexOfOutBoundsException.

    This might be more safe:

    public static void Main()
    {
        var someNumbers = new [] { 10,67,45,26,78,53,12,45,68};
        var groupNames = new [] { "A", "B", "C", "D" };
    
        var result = someNumbers.GroupBy(v => v / 25, p => p);
    
        foreach(var v in result.OrderBy(i => i.Key))
        {
            // check if the key can be used as index for the name array.
            if(v.Key >= groupNames.Length)
                Console.WriteLine(v.Key + " no name for that");
            else
                Console.WriteLine(groupNames[ v.Key]);
    
            foreach(var k in v)
                Console.WriteLine("  " + k);
        }
    
    }
    

    Look here for a live demo: https://dotnetfiddle.net/8XElaZ

    0 讨论(0)
提交回复
热议问题