将范围值分成组,例如,如果范围在0到100之间 我有四组A,B,C,D。如果我想将范围分成四组 喜欢 0-25组D. 26-50组C. 51-75组B. 76-100组A
如何使用C#进行此类分组,并将范围保存在列表中。 那么如何确定某个数字是否属于哪个组? 例如55属于B组。
请帮忙!
答案 0 :(得分:1)
您可以尝试以下方式:
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);
}
我将value / 25
上的值分组,这将是一个整数除法,并将值组合在25的部分上。例如:value 13
。 13 / 25 = 0
因此13
将按0分组。例如:value 67
。 67 / 25 = 2
,因此将按2分组。
唯一的问题是,如果值超过99,则会得到IndexOfOutBoundsException
。
这可能更安全:
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);
}
}
点击这里观看现场演示:https://dotnetfiddle.net/8XElaZ
答案 1 :(得分:0)
以下是一些示例代码可以帮助您:
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"]));