I need to look inside a collection if contains multiple elements. Can i use in statement?
Example:
public class Person
{
public int Age { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
var person = new List<Person>();
person.Add(new Person { Age = 1 });
person.Add(new Person { Age = 5 });
person.Add(new Person { Age = 2 });
person.Add(new Person { Age = 3 });
var selectedPersons = person.Where(x => x.Age in (1, 3, 5));
}
CodePudding user response:
I assume the in
is meant as you would use it in SQL-where. If you want all Age
that contain 1, 2 or 3 you would write:
var selectedPersons = person.Where(x => new [] {1, 2, 3}.Contains(x.Age));
If you want to select all persons that have an Age between 1 and 3 than you would write:
var selectedPersons = person.Where (x => x.Age >= 1 && x.Age <= 3);