【问题标题】: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 =&gt; x.JoinedDate &gt; ... &amp;&amp; x.JoinedDate &lt; ...).OrderBy(y =&gt; y.Id)?

标签: c# linq


【解决方案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

    【讨论】:

    • 不做“之间”比较
    猜你喜欢
    • 2022-09-24
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 2013-12-29
    相关资源
    最近更新 更多