Filtering Operators

Filtering operations, also known as selection, restrict result sets to only elements satisfying the condition(s) specified; for example, only retrieving values within a range of 200 to 300.

Two LINQ operator methods perform filtering operations: OfType and Where.

The OfType method selects values which conform to a specified type. It utilizes the following syntax:

public static IEnumerable<TResult> OfType<TResult>(
	this IEnumerable source

Review an example of its use below:

System.Collections.ArrayList footieshoes =
	new System.Collections.ArrayList(4);
fruits.Add("New Balance");
// Use OfType()
IEnumerable<string> query = footieshoes.OfType<string>();
Console.WriteLine("String type elements follow:");
foreach (string footieshoes in query)

It offers many practical uses such as locating form elements conforming to a specific type, e.g., all buttons or all textboxes. It also proves useful when converting collections into strongly-typed collections.

The Where method selects values which satisfy a predicate function. It utilizes the following syntax:

public static IEnumerable<TSource> Where<TSource>(
	this IEnumerable<TSource> source,
	Func<TSource, bool> predicate

Review an example of its use below:

List<string> snacks =
	new List<string> { "pear", "chocolate", "banana", "chips",
	"cashews", "jerky", "cookies", "raisins" };
IEnumerable<string> query = snacks.Where(snack => snack.Length < 6);
foreach (string snack in query)

Review another example featuring where clause use:

string[] terms = { "Javascript", "is", "not", "a", "development",
"language" };
IEnumerable<string> query = from term in terms
							where term.Length == 8
							select term;
foreach (string xyz in query)