C# 正在获取不在时间间隔内的小时的列表

C# 正在获取不在时间间隔内的小时的列表,c#,list,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, 1

我试图得到一个不在整数间隔内的小时列表。例如,如果间隔为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;
        }
List GetTimeList(列出邮件,int-TransferSpeed)
{
列表时间=新列表({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(邮件中的邮件)
{

Hours.RemoveAll(x=>x>=mail.DateAndTime.Hour&&x除了
之外,您可以使用Linq的

像这样:

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);
   }
我的第一次尝试可能看起来像这样

(虽然这种方法可以工作数小时,但它不能扩展到任意的时间分辨率。它也不太适合查看任意的日期。)


另外,作为一般性说明:对于方法的返回类型,优先选择
IReadOnlyList
IEnumerable
(例如),以防止“调用方中的意外突变”。

Enumerable.Range(1,24)
。从技术上讲,IEnumerable.Exception也可能返回相同的顺序(作为实现细节,它将用于LINQ2对象)。此外,可以跳过要排除的中间构建时间。
1,2,3,4,5,6,7,8,9,24
var hours = Enumerable.Range(1, 24);

// Build sequence of ranges of all start..end hours.
// I put in an extra Select to-anon for code clarity-of-intent.
// SelectMany takes returns of [10,11,12],[1,2],[11,12] eg.
// and turns them into a single sequence like [10,11,12,1,2,11,12]
var exclusions = Mails
    .Select(m => new {
       Start = m.DateAndTime.Hour,
       // Don't care if we run past > 24, although THIS MIGHT BE
       // A DEFECT IN THE ORIGINAL that should be addressed..
       Duration = GetRoundedTransferTime(TransferSpeed, m.Size),
    })
    // To address previous potential defect, build appropriate
    // sequence in here that understands how to 'wrap around' days.
    .SelectMany(s => Enumerable.Range(s.Start, s.Duration));

// All hours in day minus exclusion hours.
// (Exclusion ranges are already expressed as individual hours.)
return hours.Except(exclusions)
    .OrderBy(h => h) // technically not needed here
    .ToList();