Linq - 如何在列表的最大元素上应用where子句

Gon*_*alo 3 c# linq linq-to-nhibernate

  • 我有一个"人"列表
  • 每个人都有一个"类别"列表
  • Categoty有两个属性:Date和Value

我想选择Person列表,其中最后一个类别等于"B".但我不知道如何在Linq语法中编写"where子句".

我的"人"结构是:

<person>
    <id>200</id>
    <name>Peter</name>
    <age>25</age>
    <categories>
        <category>
            <date>2012-05-01<date>
            <value>A</value>
        </category>
        <category>
            <date>2013-01-01<date>
            <value>B</value>
        </category>
        <category>
            <date>2013-02-01<date>
            <value>C</value>
        </category>
    </categories>
</person>
Run Code Online (Sandbox Code Playgroud)

gun*_*171 5

您可以使用以下内容:

List<Person> allPersons = GetListOfPersons();

List<Person> selectedPersons = allPersons
    .Where((x) => x.Categories
                   .OrderBy(y => y.Date)
                   .Last()
                   .Value == "B")
    .ToList();
Run Code Online (Sandbox Code Playgroud)

或查询样式

List<Person> selectedPersons = (from person in allPersons
                                where person.Categories.OrderBy(x => x.Date).Last().Value == "B"
                                select person).ToList();
Run Code Online (Sandbox Code Playgroud)