Range division in c#

前端 未结 2 1691
执笔经年
执笔经年 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: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

提交回复
热议问题