How to use LINQ Conversion Operator “OfType”

In this How to #1, we are going to see how to use LINQ Conversion Operator “OfType” to retrieve the different types of objects from an Object array based on the type of the Object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using System.Data.SqlClient;

namespace OfTypeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Setting properties for User object user1
            User user1 = new User();
            user1.FirstName = "Mohan";
            user1.LastName = "Krishna";

            //Setting properties for User object user2
            User user2 = new User();
            user2.FirstName = "Rami";
            user2.LastName = "Vemula";

            //Declare array of diffent objects
            object[] objArray = { "Sunil", 3, 4.0, "Siva", 5, user1, 6.0, user2 };

            //Get the integer objects in the array
            var integers = objArray.OfType<int>();
            Console.WriteLine("Integer objects in the array:-");
            foreach (var i in integers)
            {
                Console.WriteLine(i);
            }

            //Get the string objects in the array
            var strings = objArray.OfType<string>();
            Console.WriteLine("\nString objects in the array:-");
            foreach (var s in strings)
            {
                Console.WriteLine(s);
            }

            //Get the Double objects in the array
            var doubles = objArray.OfType<double>();
            Console.WriteLine("\nDouble objects in the array:-");
            foreach (var d in doubles)
            {
                Console.WriteLine(d);
            }

            //Get the Custom objects(User) in the array
            var users = objArray.OfType<User>();
            Console.WriteLine("\nUser objects in the array:-");
            foreach (var user in users)
            {
                Console.WriteLine(user.FirstName+" "+user.LastName);
            }

            Console.ReadLine();
        }
    }

    class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Output:-

LinqOftype

Happy Coding!!!

You may also like...