ADVERTISEMENT
ADVERTISEMENT

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

Here, we are going to learn how to find integer numbers from the list of objects and sort them using Linq in C#?
Submitted by Nidhi, on August 29, 2020

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.

Program:

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.