C# Where Keyword: LINQ Filtering Guide
In C#, the “where” keyword is used in LINQ queries to specify one or more filtering conditions. It can be used to filter elements in a collection, returning only those that meet the specified criteria.
The basic syntax of the “where” keyword is:
var result = from item in collection
where condition
select item;
Or, alternatively, use the method syntax.
var result = collection.Where(item => condition);
In this case, item represents each element in the set, and condition is a Boolean expression used for filtering elements.
Here are some examples of using “where”:
// 从整数集合中筛选出大于5的元素
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var result = numbers.Where(n => n > 5);
// 从字符串数组中筛选出长度大于等于5且以大写字母开头的字符串
var strings = new string[] { "Apple", "banana", "cherry", "Orange", "grape" };
var result = strings.Where(s => s.Length >= 5 && char.IsUpper(s[0]));
// 从自定义对象集合中筛选出满足特定条件的对象
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
var people = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 },
new Person { Name = "Charlie", Age = 35 }
};
var result = people.Where(p => p.Age > 30);
In these examples, the ‘where’ keyword is used to filter out elements that meet specific conditions and place them into a new collection.