【问题标题】:C# - Nested LINQ queriesC# - 嵌套的 LINQ 查询
【发布时间】:2021-10-27 04:57:21
【问题描述】:

假设我有一个要过滤的对象列表:

using System;
using System.Collections.Generic;
using System.Linq;

public class Person
{
    public string Name;
    public int Age;
    public List<int> Attributes;

}
class HelloWorld
{
    static void Main()
    {
        var p1 = new Person();
        p1.Name = "john";
        p1.Attributes = new List<int> { 1, 2, 3, 6, 9 };
        p1.Age = 25;

        var p2 = new Person();
        p2.Name = "steve";
        p2.Attributes = new List<int> { 2, 5, 9, 10 };
        p2.Age = 47;

        List<Person> people = new List<Person> { p1, p2 };

        people.Where(p=>p.Age > 20)
            .Where(p=>p.Attributes ?????);
    }
}

如何查询属性超过阈值(例如 >10)的 People 对象?似乎我需要第二个查询,但我不知道如何嵌套它们。

【问题讨论】:

    标签: c# .net linq


    【解决方案1】:

    您可以使用Any()。无需使用多个Where() 子句,您可以将多个条件包含在一个Where() 子句中

    Any() :确定序列的任何元素是否存在或 满足条件。

    var thresholdValue = 10; 
    var result = people.Where(   //Filter list of people based on below conditions
                  p=>p.Age > 20 &&   //Age should be greater than 20
                  //**Atleast one** attribute should be greater than thresholdValue
                  p.Attributes.Any(x => x > thresholdValue));
    

    我使用了&amp;&amp; 运算符,因为在这个问题上,您似乎想要过滤同时满足这两个条件的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多