我有这样的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; }
}
有点像这样的价值:
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的值和日出值之间,则myTextBox应显示Fajr的值。 如果当前时间的值在日出和Zuhr之间,显示Zuhr?
如何让它在myTextBox2中显示属性名称? 例如,myTextBox显示值“07:00”,myTextBox2显示“Fajr”?
答案 0 :(得分:1)
首先,保持不是字符串而是TimeSpan对象:
public TimeSpan Fajr { get; set; }
public TimeSpan Sunrise { get; set; }
为此,将XML解析为DateTime:
TimeSpan ts = TimeSpan.Parse(c.Attribute("attr"));
所以:
TimeSpan now = DateTime.Now.TimeOfDay; // time part only
var data = filteredData.First();
string result = null;
if (data.Fajr <= now && now < data.Sunrise); // notice operators greed
result = data.Fajr;
else if (data.Sunrise <= now && now <= data.Zuhr)
result = data.Zuhr;
myTextBox.Text = result;
答案 1 :(得分:1)
首先根据@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之间:))
答案 2 :(得分:0)
这里的问题是你的代码是“字符串输入”。我会更好地使用设计时间的类型,例如DateTime,但要快速修复它:
// don't you need a third one here?
select new PrayerTime()
{
Fajr = c.Attribute("Fajr").Value,
Sunrise = c.Attribute("Sunrise").Value,
};
涂得到当前时间:
int currentHour = DateTime.Now.Hour;
然后只是两个整数的简单比较。
var data = filteredData.First();
int fajrHour = int.Parse(data.Fajr.Substring(0, 2), CultureInfo.InvariantCulture);
int sunriseHour = int.Parse(data.Sunrise.Substring(0, 2), CultureInfo.InvariantCulture);
int zuhrHour = int.Parse(data.Zuhr.Substring(0, 2), CultureInfo.InvariantCulture);
if(fajrHour <= currenHour && currenHour < sunriseHour)
{
myTextBox.Text = data.Fajr; // or to show value fajrHour.ToString()
}
if(sunriseHour <= currenHour && currenHour < zuhrHour)
{
myTextBox.Text = data.Zuhr; // zuhrHour.ToString()
}
// don't you need a third one here?