Get the best out of our app
GeeksforGeeks App
Open App
Browser
Continue

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

Given a list of objects, we need to find the integer double numbers from the list of objects and sort them using LINQ. So this task can be done using the OfType() method and then the sorting of numbers can be done by using OrderBy() method. Let discuss them one by one along with their syntax:

1. OfType() method: It is used to filter the elements of an IEnumerable according to the specified type. If the given source is null then this method will throw ArgumentNullException.

Syntax:

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

2. OrderBy() method: This method is used to sort the elements in the collection in ascending order. If the given source is null then this method also throws ArgumentNullException.

Syntax:

public static System.Linq.IOrderedEnumerable<TSource> OrderBy<TSource,TKey(

thisSystem.Collections.Generic.IEnumerable<TSource> list, Func<TSource,TKey> Selector);

Example:

```Input  : ["sai", 100, "mohan", 18, 50, 200, "rajesh", 34]
Output : [18, 34, 50, 100, 200]

Input  : ["raju", 345, 18.0 , "mohan", 189, 193, 30, 200, "rajesh"]
Output : [30, 189, 193, 200, 345]```

Approach:

• Create an list of objects using ArrayList.
• Now using the OfType<int>() method along with OrderBy() method we will select the integer values from the list and sort the integers and then convert them into a list using ToList() method.
`List<int> result = objList.OfType<int>().OrderBy(num=>num).ToList();`
• Print the list using the foreach loop.
```foreach (int integer in result)
{
Console.Write(integer + " ");
}```

## C#

 `// C# program to find the integer numbers from``// the list of objects and sort them.``using` `System;``using` `System.Linq;``using` `System.Collections.Generic;` `class` `GFG{` `static` `void` `Main(``string``[] args)``{``    ` `    ``// Declaring and initializing an arrayList``    ``// of objects``    ``List<``object``> objList = ``new` `List<``object``>(){``        ``"sai"``, 100, ``"mohan"``, 18.0, 50, 200, ``"rajesh"``, 34 };``    ` `    ``// Selecting the integers from the list and sorting``    ``// them using orderby()``    ``List<``int``> result = objList.OfType<``int``>().OrderBy(num => num).ToList();` `    ``// Printing sorted list``    ``Console.WriteLine(``"The Sorted integers are : "``);``    ``foreach` `(``int` `integer ``in` `result)``    ``{``        ``Console.Write(integer + ``" "``);``    ``}``}``}`

Output

```The Sorted integers are :
34 50 100 200 ```
My Personal Notes arrow_drop_up