Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter large list based on date time

Tags:

c#

datetime

linq

I have the following Items class:

public class Item
{
   public Item()
   {
   }

   public string Id {get; set;}
   public string Name {get; set;}
   public string Price {get; set;}
   public DateTime CreatedDate {get; set;}

}

and then in my code I have List<Item> items that contains A LOT of items of type Item, my question is what you recommend as the best way/practice of sorting/filtering the items in the list based on CreatedDate for the following scenarios:

  • all items where the CreatedDate is before date x
  • all items where the CreatedDate after date x
  • all items where the CreatedDate between date x and date y

P.S. What about if I will mentione also the time? Like before/after/between date x time y ?

like image 966
David Dury Avatar asked Aug 22 '13 08:08

David Dury


2 Answers

You can use LINQ:

var beforeDateX = items
    .Where(i => i.CreatedDate.Date < DateX); // remove the .Date if you want to include the time
var afterDateX = items
    .Where(i => i.CreatedDate.Date > DateX);
var betweenDates = items
    .Where(i => i.CreatedDate.Date >= DateX && i.CreatedDate.Date <= DateY);

You can use a foreach or methods like ToList to execute the query and materialize the result.

foreach(Item i in beforeDateX)
    Console.WriteLine("Name:{0} CreatedDate:{1}", i.Name, i.CreatedAt);
like image 92
Tim Schmelter Avatar answered Nov 14 '22 23:11

Tim Schmelter


Use Linq:

var itemsBefore = items.Where(i => i.CreatedDate <= timeBefore);
var itemsAfter = items.Where(i => i.CreatedDate >= timeAfter);
var itemsBetween = items.Where(i => i.CreatedDate >= timeStart && i.CreatedDate <= timeEnd);

For ordering

var ordrered = items.OrderBy(i => i.CreatedDate);
like image 22
Ahmed KRAIEM Avatar answered Nov 14 '22 21:11

Ahmed KRAIEM