articles

home / developersection / articles / linq where() and oftype() using c#.

LINQ where() and OfType() using C#.

LINQ where() and OfType() using C#.

Ashutosh Kumar Verma 492 12-Feb-2025

In LINQ, Where and OfType are used to filter collections, but they serve different purposes. Let's understand them with C# examples..

 

Where() in LINQ

  • Filters elements based on a condition.
  • Works with any data type.
  • Uses lambda expressions to specify conditions.

Example:

using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
   static void Main()
   {
       List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
       // Get even numbers
       var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
       Console.WriteLine("Even Numbers: " + string.Join(", ", evenNumbers));
       // Output: Even Numbers: 2, 4, 6, 8
       List<string> names = new List<string> { "Alice", "Bob", "Andrew", "Charlie" };
       var aNames = names.Where(name => name.StartsWith("A")).ToList();
       Console.WriteLine("Names starting with A: " + string.Join(", ", aNames));
       // Output: Names starting with A: Alice, Andrew
   }
}

 

OfType<T>() in LINQ

  • Filters only elements of a specific type from a collection.
  • Useful when working with collections of mixed data types.

 

Example:

 

using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
   static void Main()
   {
       List<object> mixedList = new List<object> { 1, "Hello", 3.14, 5, "World", 10 };
       var integers = mixedList.OfType<int>().ToList();
       Console.WriteLine("Integers: " + string.Join(", ", integers));
       // Output: Integers: 1, 5, 10
       var strings = mixedList.OfType<string>().ToList();
       Console.WriteLine("Strings: " + string.Join(", ", strings));
       // Output: Strings: Hello, World
   }
}

When to use What?

  • Use Where() when filtering based on conditions (for example, numbers greater than 5, strings starting with "A").
  • Use OfType<T>() when filtering based on data types in a mixed collection.

 

Also, Read: Aggregate functions in LINQ

 


Updated 12-Feb-2025

Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By