Backend Development
C#.Net Tutorial
C# program to find integers from a list of objects and sort them using LINQ
C# program to find integers from a list of objects and sort them using LINQ

Introduction
In this article, we will learn how to write a C# program to find integers from a list of objects and sort them using LINQ. Let's give a brief overview of the language. The C# programming language is frequently used to develop desktop, web, and mobile applications. Language-Integrated Query (sometimes called LINQ) is one of C#'s strengths. Developers can quickly query data from a variety of sources, including arrays, collections, and databases. It enables developers to use syntax equivalent to SQL (Structured Query Language) and supports simple data manipulation and sorting. It provides a standard syntax for data querying regardless of the data source. Since LINQ's syntax is similar to SQL, developers can easily learn and use it.
Problem Statement
In this article, we will demonstrate how to find integers from a list of objects and sort them using LINQ in C#. Integer doubles must be obtained from a list of objects and then they must be sorted. Therefore, the OfType() method can be used for this operation and the OrderBy() function can be used to sort integers. Let’s review each of them and their syntax -
OfType() method
It is used to filter the elements of IEnumerable according to the specified type. If the supplied source is null, this method throws an ArgumentNullException.
grammar
public static System.Collections.Generic.IEnumerable<TResult> OfType<TResult>(this System.Collections.IEnumerable source);
OrderBy() method
Use this technique to sort the elements in a collection in ascending order. This procedure also throws an ArgumentNullException if the supplied source is null.
grammar
public static System.Linq.IOrderedEnumerable OrderBy<TSource,TKey(thisSystem.Collections.Generic.IEnumerable<TSource> list, Func<TSource,TKey> Selector);
Let us understand this problem through an example.
Example
Create a list and add elements to it. In this example, we take objects of different data types.
enter
["Tutpoints", 100, "LINQ", 18, “50”, 20, ‘A’, 34]
For different objects, the OfType() and OrderBy() methods will sort and arrange the integer values in the list. So the output for a given input is
Output
[18, 20, 34,100]
algorithm
Step 1 − Create an object list
We first create a list of objects consisting of strings, integers and character combinations.
List<object> list = new List<object> { "Tutpoints", 100, "LINQ", 18, “50”, 20, ‘A’, 34};
Step 2 − Use OfType() method to find integers
The OfType() method will then be used to filter the list so that only integer values are retained.
var integers = list.OfType<int>();
The extension method provided by LINQ is called OfType(). It returns a filtered list of such entries. In this example, the list is filtered to contain only elements of type int. Now only the integer values from the first list appear in the integer variable.
Step 3 − Use OrderBy() to sort the integers
We can use the OrderBy() function to sort a sequence of integer values in ascending order.
var sortedIntegers = integers.OrderBy(x => x);
Another extension function provided by LINQ is OrderBy(). It sorts the list of elements in ascending order based on the given key. In this example, a lambda expression (x => x) is used to specify the key by which the series is sorted. Pass the sequence element (x) to a lambda expression, which then returns the value that will be the sort key.
The integer values in the initial list now appear in the sortedIntegers variable, in ascending order.
Step 4 −Print the sorted integers.
Finally, we can use the foreach loop and the Console.WriteLine() method to print out the sorted integer values.
This is a simple algorithm we just read about. Now let's look at a complete C# program that demonstrates how to find integers 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
in conclusion
In this article, we show you how to find integers from a list of objects and sort them using LINQ in C#. After removing all values except integer values from the list using OfType() function, we sort the integers using OrderBy() method. Finally, we use the print command to display the sorted integer values to the console. We've seen the algorithm and seen the code. We hope this article helps you enhance your knowledge and understanding of this topic.
The above is the detailed content of C# program to find integers from a list of objects and sort them using LINQ. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Optimizing C# Application Startup Time with ReadyToRun and AOT Compilation
Aug 22, 2025 am 07:46 AM
ReadyToRun(R2R)improvesstartuptimebypre-compilingILtonativecodeduringpublish,reducingJITworkloadatruntime.2.NativeAOTcompilationeliminatestheJITentirelybycompilingtheentireapptonativecodeatbuildtime,enablingnear-instantstartup.3.UseR2Rforminimal-effo
Leveraging C# for Scientific Computing and Data Analysis
Aug 05, 2025 am 06:19 AM
C#canbeusedforscientificcomputinganddataanalysisbysettingupaproperenvironment,leveragingrelevantlibraries,andoptimizingperformance.First,installVisualStudioorVSCodewiththe.NETSDKasthefoundation.Next,useNuGetpackageslikeMath.NETNumericsforlinearalgebr
Memory Management in .NET: Understanding Stack, Heap, and GC
Aug 27, 2025 am 06:25 AM
Thestackstoresvaluetypesandreferenceswithfast,automaticdeallocation;theheapholdsreferencetypeobjectsdynamically;andthegarbagecollectorreclaimsunreachableheapobjects.1.Thestackisthread-specific,limitedinsize,andstoreslocalvariables,methodparameters,an
Minimal APIs in ASP.NET Core 8: A Practical Deep Dive
Aug 22, 2025 pm 12:50 PM
MinimalAPIsin.NET8areaproduction-ready,high-performancealternativetocontrollers,idealformodernbackends.1.Structurereal-worldAPIsusingendpointgroupsandextensionmethodstokeepProgram.csclean.2.Leveragefulldependencyinjectionsupportbyinjectingservicesdir
Asynchronous Programming in C#: Common Pitfalls and Best Practices
Aug 08, 2025 am 07:38 AM
Alwaysuseasync/awaitallthewaydowninsteadofblockingwith.Resultor.Wait()topreventdeadlocksincontext-awareenvironments;2.Avoidmixingsynchronousandasynchronouscodebyensuringtheentirecallstackisasync;3.UseConfigureAwait(false)whentheoriginalcontextisn’tne
How to hash and salt a password in C#?
Aug 08, 2025 am 06:32 AM
TosecurelystorepasswordsinaC#application,youshouldhashthemwithasalt.1.UseRfc2898DeriveBytestoimplementPBKDF2,whichcombinesapassword,arandomsalt,andaniterationcounttogenerateasecurekey.2.Generatearandom16-bytesaltusingRandomNumberGenerator.3.UsePBKDF2
Mastering Multithreading in C#: A Guide to `Task`, `async`, and `await`
Aug 11, 2025 pm 12:25 PM
ThemodernapproachtomultithreadinginC#usesTask,async,andawaittosimplifyasynchronousprogrammingwithoutmanualthreadmanagement.1.Taskrepresentsanasynchronousoperation,withTaskreturningavalue,andhandlesbackgroundthreadschedulingviatheTaskParallelLibrary.2
C# Dependency Injection: From Basics to Advanced Scenarios with DI Containers
Aug 16, 2025 am 01:41 AM
DependencyInjection(DI)inC#isadesignpatternthatenablesloosecouplingbyinjectingdependenciesexternallyratherthancreatingtheminternally.1.DIpromotestestabilityandmaintainability,asseenwhenreplacingtightlycoupleddependencies(e.g.,newLogger())withconstruc


