I have a list of . I want to sort this list based on an Id property and then filter items based on a JoinedDate property. How do I use Linq here.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime JoinedDate { get; set; }
}
static void Main (string[] args)
{
List<Person> persons = new List<Person> ();
var date1 = new DateTime (2021, 1, 1);
var date2 = new DateTime (2021, 2, 1);
var date3 = new DateTime (2021, 3, 1);
var date4 = new DateTime (2021, 4, 1);
persons.Add(new Person {Id = 1, JoinedDate = date1, Name = "John"});
persons.Add (new Person { Id = 2, JoinedDate = date2, Name = "Tim" });
persons.Add (new Person { Id = 3, JoinedDate = date3, Name = "Karl" });
persons.Add (new Person { Id = 4, JoinedDate = date4, Name = "Jim" });
// I have Two dates
// From and To
// Need to Created a list of person whose JoinedDate is between From and To data
List<Person> filteredPersons = new List<Person> ();
}
CodePudding user response:
var filteredPersons = persons
.Where(person =>
person.JoinedDate >= from && person.JoinedDate <= to)
.OrderBy(person => person.Id)
.ToList();
Is all you need, I think.
CodePudding user response:
If you want to be specific with the joined date, you can use the code below:
persons.Where(person=>person.JoinedDate==new DateTime(year,month,day)).OrderBy(person=>person.Id).ToList()
PS. For clarity purposes, please rename your list to people.