문제

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