C# - Find integers from objects list and sort them using LINQ

Learn, how to find integer numbers from the list of objects and sort them using Linq in C#? By Nidhi Last updated : April 01, 2023

Here, we will create a list of objects and then find integer numbers using the OfType() method and then sort integer numbers using OrderBy() method and then print them on the console screen.

C# program to find integer numbers from the list of objects and sort them using LINQ

The source code to find integer numbers from the list of objects and sort them using Linq is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# Program to find integer numbers from the 
//list of objects and then sort them in ascending order 
//using Linq.

using System;
using System.Linq;
using System.Collections.Generic;

class Demo {
  static void Main(string[] args) {
    List <object> objectList = new List <object> () {
      301,
      "Amit",
      202,
      "Joseph",
      805,
      "RK Verma",
      120,
      "Sanjay Shukla",
      407,
      "Pramod Pandey",
      405
    };

    List <int> result = objectList.OfType <int> ().OrderBy(num => num).ToList();

    Console.WriteLine("Sorted integers: ");
    foreach(int val in result) {
      Console.Write(val + " ");
    }
    Console.WriteLine();
  }
}

Output

Sorted integers:
120 202 301 405 407 805
Press any key to continue . . .

Explanation

In the above program, we created a class Demo that contains the Main() method. In the Main() method we created a list of objects that contains integer and string values.

List<int> result = objectList.OfType<int>().OrderBy(num=>num).ToList();

In the above code, we find integers using the OfType() method and sort them using OrderBy() method.

Console.WriteLine("Sorted integers: ");
foreach (int val in result)
{
    Console.Write(val + " ");
}
Console.WriteLine();

In the above code, we accessed the filtered values one by one and print it on the console screen.

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.