Scroll to top

C# Language : LINQ Queries


Curious Bot - December 1, 2018 - 0 comments

LINQ is an acronym which stands for Language INtegrated Query. It is a concept which integrates a query language by offering a consistent model for working with data across various kinds of data sources and formats; you use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for which a LINQ provider is available.

Where

Returns a subset of items which the specified predicate is true for them.

List<string> trees = new List<string>{ "Oak", "Birch", "Beech", "Elm", "Hazel", "Maple" };

Method syntax

// Select all trees with name of length 3
var shortTrees = trees.Where(tree => tree.Length == 3); // Oak, Elm

Query syntax

var shortTrees = from tree in trees
where tree.Length == 3
select tree; // Oak, Elm

Select – Transforming elements

Select allows you to apply a transformation to every element in any data structure implementing IEnumerable.

Getting the first character of each string in the following list:

List<String> trees = new List<String>{ "Oak", "Birch", "Beech", "Elm", "Hazel", "Maple" };

Using regular (lambda) syntax

//The below select stament transforms each element in tree into its first character.
IEnumerable<String> initials = trees.Select(tree => tree.Substring(0, 1));
foreach (String initial in initials) {
System.Console.WriteLine(initial);
}

Output:

O
B
B
E
H
M

Live Demo on .NET Fiddle

Using LINQ Query Syntax

initials = from tree in trees
select tree.Substring(0, 1);

Chaining methods

Many LINQ functions both operate on an IEnumerable<TSource> and also return an IEnumerable<TResult>. The type parameters TSource and TResult may or may not refer to the same type, depending on the method in question and any functions passed to it.

A few examples of this are

public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector

Related posts