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:
P.S. What about if I will mentione also the time? Like before/after/between date x time y ?
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With