从另一个排序列表创建过滤列表
Posted
技术标签:
【中文标题】从另一个排序列表创建过滤列表【英文标题】:Create a filtered list from another sorted list 【发布时间】:2022-01-02 20:39:57 【问题描述】:我有一个 .我想根据 Id 属性对该列表进行排序,然后根据 JoinedDate 属性过滤项目。我如何在这里使用 Linq。
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> ();
【问题讨论】:
persons.Where(x => x.JoinedDate > ... && x.JoinedDate < ...).OrderBy(y => y.Id)
?
【参考方案1】:
var filteredPersons = persons
.Where(person =>
person.JoinedDate >= from && person.JoinedDate <= to)
.OrderBy(person => person.Id)
.ToList();
我想这就是你所需要的。
【讨论】:
【参考方案2】:已修复,由 @Crowcoder 建议
persons.Where(person=>person.JoinedDate > new DateTime(year,month,day) && person.JoinedDate < new DateTime(year, month, day)).OrderBy(person=>person.Id).ToList()
PS。为清楚起见,请将您的列表重命名为 people。
【讨论】:
不做“之间”比较以上是关于从另一个排序列表创建过滤列表的主要内容,如果未能解决你的问题,请参考以下文章