c# - How to get next active item in a list with LINQ -
I have a small problem where I want to find the next "active" item in the list with linq. Then the next "active" item is defined by the start date and enddate. Here is an example list.
// - IList and lt; Turn & gt; Varies = new list & lt; Turn & gt; () {New turn () {name = "turn 1", StartDate = DateTime.Parse ("2009-05-01"), endadat = datetime.parse ("2009-05-01"), new turn () { Name = "turn 2", start date = date time. Purse ("2009-06-01"), enddate = datetime. Purse ("2009-06-01")}, New Turn () {Name = "Turn 3", StartDate = DateTime.Parse ("2009-07-01"), EndDate = DateTime.Parse ("2009-07- 02 ")}, New Turn () {Name =" Turn 4 ", StartDate = DateTime.Parse (" 2009-08-01 "), EndDate = DateTime.Parse (" 2009-08-03 ")}} // - Get a next turn by date. Date time up to date = date time.ps ("2009-06-02"); // - "Turn 3" items should return ... rotate = (turn item into where turn select .....) .FirstOrDefault & lt; Turn & gt; (); Turn on, using a startDate / endDate property is a good way to find the next turn I have tried to start the list from the list for the first time and to find the first one in the list Have tried, but I feel that if there is a "safe" way to get it, then the list is not needed in order to find the correct turn.
Why do not you get the first thing with the date of the beginning of today? I added an explanation OrderBy () call to make sure the list is sorted. If you know that it has been sorted, you can leave it.
turns.OrderBy (t = & gt; t.StartDate). FirstOrDefault (t = & gt; t.StartDate> today); UPDATE
I missed your previous lines. Yes, you can do this without clearly sorting the list After the start date, the item should be searched for the item and there should be no items with the date of the beginning of today, but before the existing item. But this will really slow down the search because you will have to look at the entire list for each item while making O (N2).
changes. Single (t = & gt; t.StartDate & gt; today and turns it all. (U = & gt; u.StartDate & lt; = Today || u.StartDate & gt; t.StartDate)) It believes that turn non-overlapping. If they overlap, then you should use single instead of first or add additional constraints to get a unique result. And finally: Use the sorting solution - This solution is not safe from sorting in any way and receiving the first item.
Comments
Post a Comment