LINQ query syntax helps you easily find and work with data inside collections like lists or arrays. It looks like writing simple questions to get the data you want.
0
0
LINQ query syntax in C Sharp (C#)
Introduction
When you want to select specific items from a list based on a condition.
When you need to sort data in ascending or descending order.
When you want to group items by a shared property.
When you want to join two collections based on matching keys.
When you want to transform data from one form to another.
Syntax
C Sharp (C#)
var result = from item in collection
where condition
orderby item.Property
select item;from starts the query and picks each item from the collection.
where filters items by a condition (optional).
Examples
Selects even numbers from the list.
C Sharp (C#)
var evens = from num in numbers
where num % 2 == 0
select num;Sorts names alphabetically.
C Sharp (C#)
var sortedNames = from name in names
orderby name
select name;Groups words by their length.
C Sharp (C#)
var grouped = from word in words
group word by word.Length;Sample Program
This program selects fruits with names 5 letters or shorter, sorts them alphabetically, and prints each one.
C Sharp (C#)
using System; using System.Linq; class Program { static void Main() { string[] fruits = { "apple", "banana", "cherry", "date", "fig", "grape" }; var shortFruits = from fruit in fruits where fruit.Length <= 5 orderby fruit select fruit; foreach (var fruit in shortFruits) { Console.WriteLine(fruit); } } }
OutputSuccess
Important Notes
You can skip where if you want all items.
Use orderby to sort results; add descending for reverse order.
LINQ query syntax is easy to read and write, especially for beginners.
Summary
LINQ query syntax lets you ask questions about collections in a clear way.
You can filter, sort, group, and select data easily.
It reads like simple English sentences, making code easier to understand.