Q:

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

belongs to collection: C# LINQ Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# LINQ Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to demonstrate the example of Linq Inte... >>
<< C# program to sort a list of employees based on sa...