Home > Back-end >  C# - Nested LINQ queries
C# - Nested LINQ queries

Time:10-27

Let's say I have a list of objects that I want to filter:

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 ?????);
    }
}

How would I query for People objects with an Attribute over a threshold (say >10)? It seems like I would need a 2nd query but I can't figure out how to nest them.

CodePudding user response:

You can use Any(). No need to use multiple Where() clause, you can include multiple conditions into one Where() clause

Any() : Determines whether any element of a sequence exists or satisfies a condition.

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));

I used && operator because in question it looks like you want to filter people which satisfies both the condition.

  • Related