Filtering operators are used to filter sequences of data based on specific conditions in LINQ (Language Integrated Query). Filtering operators like Where and OfType are commonly used in LINQ (Language Integrated Query).
The Where operator filters a sequence of values based on a predicate. It allows you to specify a condition that each element must satisfy to be included in the result set.
Example
In this example, the Where operator filters the list of numbers to include only even numbers.
using System;
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Using Where to filter even numbers
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var num in evenNumbers)
{
Console.WriteLine(num); // Output: 2, 4, 6, 8, 10
}
Console.ReadKey();
}
}
}
Output
In this example, the Where operator filters the list of numbers to include only even numbers.
The OfType operator filters the elements of an IEnumerable based on a specified type. It is useful when you have a collection of objects of different types and you want to select elements of a particular type.
Example
In this example, the OfType operator filters the list to include only elements of type int.
using System;
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
List<object> mixedList = new List<object> { 1, "two", 3, "four", 5 };
// Using OfType to filter integers
var integers = mixedList.OfType<int>();
foreach (var num in integers)
{
Console.WriteLine(num); // Output: 1, 3, 5
}
Console.ReadKey();
}
}
}
Output
In this example, the OfType operator filters the list to include only elements of type int.