查找c#中以xml为数据源的两个输入日期之间的所有日期



我正在asp.net中使用XML作为数据源的应用程序,其中我要求用户以"dd/MM"的形式从2个文本框中输入2个日期,而不包括年份。我需要找到生日在这个日期范围内的员工的所有详细信息。XML包含所有员工的详细信息,DOB以"dd/MM"的形式保存。我尝试了不同的逻辑,但都没有成功。所以请建议我如何解决这个问题。提前感谢。

我在注释中指定了一种简单的方法。使用Linq,它可以像下面这样使用。

namespace Test {
public class BirthdayTest
{
    public HasBirthday[] birthdays = new[] {
        new HasBirthday { Name = "Name1", Birthday = new DateTime(2014, 1, 1) },
        new HasBirthday { Name = "Name2", Birthday = new DateTime(2014, 2, 14) }
    };
    public class HasBirthday {
        public DateTime Birthday { get; set; }
        public string Name { get; set; }
    }
    public IEnumerable<HasBirthday> InRange(string from, string to) {
        int firstMonth = Int32.Parse(from.Substring(3));
        int lastMonth = Int32.Parse(to.Substring(3));
        int firstDay = Int32.Parse(from.Substring(0, 2));
        int lastDay = Int32.Parse(to.Substring(0, 2));
        IEnumerable<HasBirthday> inRange = birthdays
            .Where(birthday =>
           birthday.Birthday.Month <= lastMonth &&
           birthday.Birthday.Month >= firstMonth &&
           (birthday.Birthday.Month != lastMonth || birthday.Birthday.Day <= lastDay) &&
           (birthday.Birthday.Month != firstMonth || birthday.Birthday.Day >= firstDay));
        return inRange;
    }
}
}

然后用你的两个日期以"dd/MM"的形式调用它。注意最后一个"split"在划分年份。

string from = "01/01";
string to = "31/12";
Console.WriteLine("between {0} and {1}", from, to);
foreach (HasBirthday birthday in InRange(from, to)){
    Console.WriteLine("{0}, {1}", birthday.Name, birthday.Birthday);
}
from = "01/02";
to = "31/12";
Console.WriteLine("between {0} and {1}", from, to);
foreach (HasBirthday birthday in InRange(from, to)){
    Console.WriteLine("{0}, {1}", birthday.Name, birthday.Birthday);
}
from = "01/12";
to = "02/01";
Console.WriteLine("between {0} and {1}", from, to);
foreach (HasBirthday birthday in InRange(from, "31/12")){
    Console.WriteLine("{0}, {1}", birthday.Name, birthday.Birthday);
}
foreach (HasBirthday birthday in InRange("01/01", to)){
    Console.WriteLine("{0}, {1}", birthday.Name, birthday.Birthday);
}
输出:

between 01/01 and 31/12
Name1, 1/1/2014 12:00:00 AM
Name2, 2/14/2014 12:00:00 AM
between 01/02 and 31/12
Name2, 2/14/2014 12:00:00 AM
between 01/12 and 02/01
Name1, 1/1/2014 12:00:00 AM

相关内容

  • 没有找到相关文章