c# - 获取不在间隔内的小时列表

标签 c# list

我正在尝试获取非整数区间的小时列表。例如,如果间隔是 10 到 23,它应该返回 [1,2,3,4,5,6,7,8,9,24]。

我写了这个方法。

List<int> GetTimeList(List<Mail> Mails, int TransferSpeed)
        {
            List<int> Hours = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };

            foreach (Mail mail in Mails)
            {
                Hours.RemoveAll(x => x >= mail.DateAndTime.Hour && x <= GetRoundedTransferTime(TransferSpeed, mail.Size));
            }
            return Hours;
        }

它实际上工作正常,但我正在寻找更优雅、更高效的方式。

如果你能帮我解决这个问题,我将不胜感激。

最佳答案

您可以使用 Linq 的 Except

像这样:

List<int> intervals=new List<int>
{
      10,11,12,13,14,15,16,17,18,19,20,21,22,23
 };

List<int> Hours = Enumerable.Range(1,24).ToList();

 var NotInIntervals=Hours.Except(intervals).ToList();

 foreach(var hour in NotInIntervals.OrderBy(x=>x))
  {
       Console.WriteLine(hour);
   }

结果

1,2,3,4,5,6,7,8,9,24

关于c# - 获取不在间隔内的小时列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203289/

相关文章:

c# - 与 MimeMapping.GetMimeMapping 相反?

c# - 使用 C# 将时间数据插入 SQL Server

c# - Listpicker 多选和 DisplayMemberPath

python - 使用作为输入输入的后缀命名输出变量

python复制嵌套列表

c# - 当发出同步 I/O 调用时,当前线程 (C#) 的 ThreadState 是什么?

c# - 如何从键盘读取 "Enter"退出程序

python - 在 Ruby 和 Python 中使用 yield 创建列表

python - 如何将文本列表乘以整数列表并得到一长串文本?

python - 在列表中搜索字典