将整数数组排序为4 &5倍表c#

本文关键字:5倍表 整数 数组排序 | 更新日期: 2023-09-27 18:03:46

我想知道解决这个问题的最佳方法。我有一个整数数组(比如3、4、8、10、15、24、29、30),我想把它分成3组:4次表,5次表,两者都不是。

正如组所建议的那样,它将数组排序到4次表和5次表中,另一个用于不存在于这两个表中的项。

在c#中实现这个的最好方法是什么?我目前正在使用这个:
          int[] iArray = new int[]{3, 4, 8, 10, 15, 24, 29, 30};
        var iE = iArray.GroupBy ((e) => {
            if (e % 4 == 0) {
                return "four";
            } else if (e % 5 == 0) {
                return "five";
            } else {
                return "other";
            }
        }).OrderBy (e => e.Count ());

生产:

4

4824

5

101530

其他

329日

将整数数组排序为4 &5倍表c#

int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };

如果您想获得所有 4的倍数和所有 5的倍数(并且两者之间有一些重叠),您可以这样做:

List<int> multiplesOf4 = (from i in arr where i % 4 == 0 select i).ToList();
List<int> multiplesOf5 = (from i in arr where i % 5 == 0 select i).ToList();
List<int> others = (from i in arr where i % 5 != 0 && i % 4 != 0 select i).ToList();

如果你想要没有重叠,你需要选择哪一个是主导的。这里我选择了4:

List<int> multiplesOf4 = new List<int>(),
          multiplesOf5 = new List<int>(),
          others       = new List<int>();
foreach (int i in arr)
{
    if (i % 4 == 0)
        multiplesOf4.Add(i);
    else if (i % 5 == 0)
        multiplesOf5.Add(i);
    else
        others.Add(i);
}

试试这个:

var numberGroupsTimes5 =
            from n in numbers
            group n by n % 5 into g
            where g.Key == 0
            select new { Remainder = g.Key, Numbers = g };
var numberGroupsTimes4 =
            from n in numbers
            group n by n % 4 into g
            where g.Key == 0
            select new { Remainder = g.Key, Numbers = g };
foreach (var g in numberGroupsTimes5)
{
     string st = string.Format("Numbers with a remainder of {0} when divided by 5:" , g.Remainder);
     MessageBox.Show("" + st);
     foreach (var n in g.Numbers)
     {
          MessageBox.Show(""+n);
     }
} 
foreach (var g in numberGroupsTimes4)
{
     string st = string.Format("Numbers with a remainder of {0} when divided by 4:", g.Remainder);
     MessageBox.Show("" + st);
     foreach (var n in g.Numbers)
     {
         MessageBox.Show("" + n);
     }
} 

你的做法是正确的。但你可以做一些小的改进,使它更可读和标准:

var iArray = new[] { 3, 4, 8, 10, 15, 24, 29, 30 };//Don't need to give type(int) explicitly
var iE = iArray.GroupBy(e => e % 4 == 0 ? "four" : e % 5 == 0 ? "five" : "other").OrderBy(e => e.Count());

它会给出相同的结果