What is LINQ in C# : Beginner's Guide
In C#, we frequently work with collections like lists and arrays. Often, we need to sort, filter, or extract specific items from these collections. LINQ is a feature that allows us to perform such operations in a clean and intuitive way.
LINQ stands for Language Integrated Query. Literally, it means “query integrated into the language.”
The word query means "a question" or "a request." In programming, it refers to asking for certain data based on a condition. In SQL, we query a database to request specific records. In LINQ, we query collections like lists or arrays to get the items we want.
LINQ brings SQL-like syntax and functionality directly into C#, making it easier to write complex data manipulations with minimal code.
Basic Sorting with LINQ
List<int> scores = new List<int> { 70, 50, 90, 30 };
// Sort ascending
var asc = scores.OrderBy(x => x).ToList();
// Sort descending
var desc = scores.OrderByDescending(x => x).ToList();
In the example above, x => x
means "sort by the value itself."
This works because integers can be compared directly.
The ToList()
method creates a new list that holds the sorted result.
Note: The original list scores
remains unchanged.
LINQ does not modify the source list; it returns a new sorted result. This is one of LINQ’s strengths—it preserves the original data.
Sorting by Object Properties
Let’s consider a simple class named Player
:
class Player
{
public string Name;
public int Level;
}
We can sort a list of players by name or level:
var players = new List<Player>
{
new Player { Name = "Alice", Level = 12 },
new Player { Name = "Charlie", Level = 15 },
new Player { Name = "Bob", Level = 20 }
};
// Sort by name (ascending)
var sortedByName = players.OrderBy(x => x.Name).ToList();
// Sort by level (descending)
var sortedByLevel = players.OrderByDescending(x => x.Level).ToList();
Here, x => x.Name
and x => x.Level
indicate that the sorting should be done based on the corresponding property of the object.
Summary
LINQ allows you to query collections in C# just like SQL queries a database.
Using OrderBy
and related methods, you can sort data with minimal code.
Since LINQ doesn’t modify the original list, it’s safe and reusable for other logic as well.
Understanding LINQ from simple examples like sorting helps build a strong foundation.
Once comfortable, you can explore Where
, Select
, FirstOrDefault
and other powerful operators.