Вопрос

I have a following code:

public string startTime = "0900";
public string closeTime = "1730";


public class TimesInfo
{
    public string Code { get; set; }
    public DateTime startTime { get; set; }
    public DateTime closeTime { get; set; }
}

Sample data:

List<TimesInfo> list = new List<TimesInfo>();
list.Add(new TimesInfo { EmpCode = "101", startTime=”2011-04-28 10:00”, closeTime=”2011-04-28 12:00” });
list.Add(new TimesInfo { EmpCode = "102", startTime=”2011-04-28 09:00”, closeTime=”2011-04-28 17:00” });
list.Add(new TimesInfo { EmpCode = "103", startTime=”2011-04-28 10:00”, closeTime=”2011-04-28 18:00” });
list.Add(new TimesInfo { EmpCode = "104", startTime=”2011-04-28 11:00”, closeTime=”2011-04-28 16:00” });

I would like to find List<TimesInfo> which is between startTime and closeTime.

So from above list we should be able to retrieve all the employee except code 103 because 18:00 is later than 17:00.

Это было полезно?

Решение

You should first parse the strings to TimeSpan

TimeSpan start = TimeSpan.ParseExact(startTime, "hhmm", CultureInfo.InvariantCulture);
TimeSpan close = TimeSpan.ParseExact(closeTime, "hhmm", CultureInfo.InvariantCulture);

then you can use this LINQ query:

List<TimesInfo> inRange = list
 .Where(ti => ti.startTime.TimeOfDay >= start && ti.closeTime.TimeOfDay <= close)
 .ToList();

Другие советы

The cleanest way is to make startTime and closeTime (the variables, not the class members) TimeSpan objects. Then you can just compare them to the TimeOfDay of the DateTime members:

list.Where(ti => ti.startTime.TimeOfDay >= startTime &&
                 ti.closeTime.TimeOfDay <= closeTime)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top