Range division in c#

前端 未结 2 1689
执笔经年
执笔经年 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"]));   
    

提交回复
热议问题