[英]Range division in c#
將范圍值分組,例如,如果范圍在 0 到 100 之間,並且我有四個組 A、B、C、D。 如果我想將范圍分為四組,例如 0-25 組 D 26-50 組 C 51-75 組 B 76-100 組 A
如何使用 C# 進行此類分組,並將范圍保存在列表中。 那么如何確定某個數字是否屬於哪個組呢? 例如 55 屬於 B 組。
請幫忙!
你可以嘗試這樣的事情:
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
上的value / 25
分組,這將是一個整數除法,並將值分組為 25 的部分。例如: value 13
。 13 / 25 = 0
所以13
將按13 / 25 = 0
分組。例如:值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
下面是一些更多的示例代碼來幫助你:
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"]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.