C# Program to Find Integer Numbers from the List of Objects and Sort them Using LINQ


Introduction

In this article, we will learn how to write a C# program to find integer numbers from the list of objects and sort them using LINQ. Let's have a small overview of the language. The C# programming language is frequently used to develop desktop, web, and mobile apps. Linguistic Integrated Query, sometimes known as LINQ, is one of C#'s strong points. Developers may quickly query data from various sources, including arrays, collections, and databases. It gives developers access to a syntax that is comparable to SQL (Structured Query Language) and enables simple data manipulation and sorting. Regardless of the data source, it offers a standard syntax for data queries. As LINQ's syntax is similar to SQL's, developers can learn and utilize it with ease.

Problem Statement

In this article, we will demonstrate how to find integer numbers from a list of objects and sort them using LINQ in C#. The integer double numbers must be taken from a list of objects and they must be sorted then. So, the OfType() method can be used for this operation, and the OrderBy() function can be used to sort the integers. Let's go over each of them individually along with their syntax −

OfType() Method

It is used to filter an IEnumerable's elements based on the specified type. This method will throw the ArgumentNullException exception if the provided source is null.

Syntax

public static System.Collections.Generic.IEnumerable<TResult> OfType<TResult>(this System.Collections.IEnumerable source); 

OrderBy() Method

The elements in the collection are sorted using this technique in ascending order. ArgumentNullException is also thrown by this procedure if the provided source is null.

Syntax

public static System.Linq.IOrderedEnumerable
OrderBy<TSource,TKey(thisSystem.Collections.Generic.IEnumerable<TSource> list, Func<TSource,TKey> Selector); 

Let’s understand the problem with an example.

Example

Create a List and add elements to it. In this example, we are taking objects of different data types.

Input

["Tutpoints", 100, "LINQ", 18, “50”, 20, ‘A’, 34] 

Out of the different objects, the OfType() and OrderBy() methods will sort and arrange the integer value from the list. So the output for the given input is

Output

[18, 20, 34,100]

Algorithm

Step 1  Creating a List of Objects

Let's begin by creating a list of objects that consists of a combination of strings and integers and chars.

List<object> list = new List<object> { "Tutpoints", 100, "LINQ", 18, “50”, 20, ‘A’, 34}; 

Step 2  Using OfType() method to Find Integer Numbers

The OfType() method will then be used to filter the list such that only the integer values remain.

var integers = list.OfType<int>(); 

The extension method offered by LINQ is called OfType(). It gives back a filtered list of entries of that kind. In this instance, the list is being filtered to only contain elements of type int. Only the integer values from the first list are now present in the integers variable.

Step 3  Using OrderBy() to Sort Integer Numbers

We can use the OrderBy() function to sort a sequence of integer values into ascending order.

var sortedIntegers = integers.OrderBy(x => x); 

Another extension function offered by LINQ is the OrderBy() one. Based on a given key, it ascendingly sorts a list of elements. In this instance, the key by which to sort the series is specified using lambda expression (x => x). A sequence element (x) is passed to the lambda expression, which then returns the value that will be the sorting key.

The integer values from the initial list are now present in the sortedIntegers variable, arranged in ascending order.

Step 4  Print the Sorted Integer Numbers.

Finally, we can print out the sorted integer values using a foreach loop and the Console.WriteLine() method.

This is a simple algorithm we have just read. Now let us look at the complete C# program that demonstrates how to find integer numbers from a list of objects and sort them using LINQ.

Example

using System;
using System.Collections.Generic;
using System.Linq;
class Program {
   static void Main(string[] args) {
      List<object> list = new List<object> { "Tutpoints", 100, "LINQ", 18, "50", 20, 'A', 34 };
      var integers = list.OfType<int>();
      var sortedIntegers = integers.OrderBy(x => x);
      Console.WriteLine("Sorted integer values are:");
      foreach (int integer in sortedIntegers) {
         Console.WriteLine(integer);
      }
   }
} 

Output

Sorted integer values are:
18
20
34
100

Conclusion

In this post, we've shown you how to use LINQ in C# to find integer numbers from a list of objects and sort them. After removing all but integer values from the list using the OfType() function, we sorted the integers using the OrderBy() method. Lastly, we used a print command to display the sorted integer values to the console. We have gone through the algorithm and also saw the code. We hope that this article helped you to enhance your knowledge and understanding of the topic.

Updated on: 21-Apr-2023

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements