简体   繁体   English

查找数字数组中缺少的元素

[英]Find missed elements in array of numbers

I have array with numbers 1...31 (days at month) On my side I would like to find all missed numbers. 我有数字为1 ... 31(每月的天数)的数组在我这边,我想查找所有遗漏的数字。 This my solution but I not sure that is a good way. 这是我的解决方案,但我不确定这是个好方法。

var result = new List<int>();
int[] days = GetSelectedDays(); //I recive array with 1..31 with some missing elements sometimes (without "5" as example it depends if user has selected this number)
for (int i=0; i <30; i++)
{
  if (!days.Contains(i))
  result.Add(i);
}

您可以使用LINQ Except

var result = Enumerable.Range(1, 31).Except(days);

Looks like you are currently checking numbers in the range 0..29 as opposed to 1..31. 看起来您当前正在检查范围为0..29而不是1..31的数字。 The only suggestion I have is to change the for loop to: 我唯一的建议是将for循环更改为:

for (int i=1; i <= 31; i++) 对于(int i = 1; i <= 31; i ++)

First off, when you're adding days of a month its probably easier to loop through a loop of DateTimes, ie 首先,当您添加一个月中的某几天时,可能更容易遍历DateTimes循环,即

var missedDateDictionary = new Dictionary<DateTime, bool>(); // or other value
var date = new DateTime(2016, 01, 01);

for (int i = 0 ; i < 32 ; i++)
{
    var newDate = date.AddDays(i);

    //do something with adding / not adding date

    if (notDoneSomething)
        missedDateDictionary.Add(newDate, true)
}

The premise here is that each DateTime you're adding is unique. 这里的前提是您要添加的每个DateTime是唯一的。

If you cant guarantee that, your solution is pretty efficient but could use some optimization. 如果不能保证,您的解决方案将非常有效,但可以使用一些优化。

  1. Initialize arary with max value: int[31] days = GetSelectedDays(); 用最大值初始化Arary: int[31] days = GetSelectedDays();

  2. A month can have 31 days: for (int i = 1; i <32; i++) 一个月可以有31天: for (int i = 1; i <32; i++)

  3. If at all possible, fill result in the loop you're filling GetSelecteDays() 如果可能,将result填充到您正在填充GetSelecteDays()的循环中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM