c# - 如何使 if 语句显示基于当前时间的 xml 属性

标签 c# xml linq linq-to-xml datetime-comparison

我有这样一个 XML:

<PrayerTime
    Day ="1" 
    Month="5" 
    Fajr="07:00" 
    Sunrise="09:00"
    Zuhr="14:00"
/>

像这样的类:

public class PrayerTime
{   
    public string Fajr { get; set; }
    public string Sunrise { get; set; }
    public string Zuhr { get; set; }
}

还有一些像这样获得值(value)的东西:

XDocument loadedCustomData = XDocument.Load("WimPrayerTime.xml");
var filteredData = from c in loadedCustomData.Descendants("PrayerTime")
                   where c.Attribute("Day").Value == myDay.Day.ToString()
                   && c.Attribute("Moth").Value == myDay.Month.ToString()
                   select new PrayerTime()
                   {
                       Fajr = c.Attribute("Fajr").Value,
                       Sunrise = c.Attribute("Sunrise").Value,
                   };
myTextBox.Text = filteredData.First().Fajr;

我如何根据一天中的当前时间说如果时间介于 Fajr 值和 Sunrise 值之间,那么 myTextBox 应该显示 Fajr 值。 如果当前时间值在日出和 Zuhr 之间,是否显示 Zuhr?

如何让它在 myTextBox2 中显示属性名称? 例如,myTextBox 显示值“07:00”,而 myTextBox2 显示“Fajr”?

最佳答案

首先按照@abatischcev 修改类

public class PrayerTime
{
    public TimeSpan Fajr { get; set; }
    public TimeSpan Sunrise { get; set; }
    public TimeSpan Zuhr { get; set; }
}

然后修改linq查询选择部分为:

select new PrayerTime()
{
    Fajr = TimeSpan.Parse(c.Attribute("Fajr").Value),
    Sunrise = TimeSpan.Parse(c.Attribute("Sunrise").Value),
    Zuhr = TimeSpan.Parse(c.Attribute("Zuhr").Value)
};

那么你的支票应该是:

var obj = filteredData.First();
TimeSpan currentTime = myDay.TimeOfDay;
string result = String.Empty;
if (currentTime >= obj.Fajr && currentTime < obj.Sunrise)
{
    result = "Fajar";
}
else if (currentTime >= obj.Sunrise && currentTime < obj.Zuhr)
{
    result = "Zuhar";
}
textbox1.Text = result;

(顺便说一下,Zuhr 时间应该在 Zuhr 和 Asar 之间 :))

关于c# - 如何使 if 语句显示基于当前时间的 xml 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485767/

相关文章:

c# - 比较带引号的字符串

android - 固定页脚不显示最底部的列表项

xml - 如何在 ruby​​ 中进行 XMLRPC::Client 的有线转储?

c# - 反转字典中的键和值

c# - NHibernate、CaSTLe、Linq 之间的区别——它们针对的是谁?

c# - 与可为空的外键的一对一关系

c# - 可选参数和方法重载

C# LINQ 组合数学 : All Combinations of a Set without the Empty Set

c# - 页面在 localhost 上加载,但不在 Azure 网站中加载 - 错误 500

java - 我的 fragment 在替换时重叠