Skip to content

C# System.Linq API

C# LINQ — a set of extension methods for querying IEnumerable<T> sequences with a declarative syntax.

1 class · 7 methods

Enumerable

7 methods

Provides a set of static methods for querying objects that implement IEnumerable<T>.

Enumerable.Where<TSource>(IEnumerable<TSource>, Func<TSource, bool>) -> IEnumerable<TSource>

Filters a sequence of values based on a predicate.

Parameters

NameTypeDescription
sourceIEnumerable<TSource>Sequence to filter.
predicateFunc<TSource, bool>Function to test each element.

Returns

IEnumerable<TSource>

Example

csharp
int[] nums = { 1, 2, 3, 4, 5 };
var evens = nums.Where(x => x % 2 == 0);
// evens == [2, 4]
Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>) -> IEnumerable<TResult>

Projects each element of a sequence into a new form.

Parameters

NameTypeDescription
sourceIEnumerable<TSource>Sequence to project.
selectorFunc<TSource, TResult>Transform function.

Returns

IEnumerable<TResult>

Example

csharp
int[] nums = { 1, 2, 3 };
var squares = nums.Select(x => x * x);
// squares == [1, 4, 9]
Enumerable.OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>) -> IOrderedEnumerable<TSource>

Sorts the elements of a sequence in ascending order according to a key.

Parameters

NameTypeDescription
sourceIEnumerable<TSource>Sequence to sort.
keySelectorFunc<TSource, TKey>Function to extract a key.

Returns

IOrderedEnumerable<TSource>

Example

csharp
var people = new[] { new {Name="Bob", Age=30}, new {Name="Ann", Age=25} };
var sorted = people.OrderBy(p => p.Age);
// Ann(25), Bob(30)
Enumerable.Sum(IEnumerable<int>) -> int

Computes the sum of a sequence of int values.

Parameters

NameTypeDescription
sourceIEnumerable<int>Sequence to sum.

Returns

int

Example

csharp
int[] nums = { 1, 2, 3, 4 };
int total = nums.Sum();  // 10
Enumerable.Count<TSource>(IEnumerable<TSource>) -> int

Returns the number of elements in a sequence.

Parameters

NameTypeDescription
sourceIEnumerable<TSource>Sequence to count.

Returns

int

Example

csharp
int[] nums = { 1, 2, 3, 4, 5 };
int n = nums.Count();  // 5
Enumerable.First<TSource>(IEnumerable<TSource>) -> TSource

Returns the first element of a sequence. Throws if the sequence is empty.

Parameters

NameTypeDescription
sourceIEnumerable<TSource>Sequence to take the first element of.

Returns

TSource

Example

csharp
int[] nums = { 5, 3, 1 };
int first = nums.First();  // 5
Enumerable.Distinct<TSource>(IEnumerable<TSource>) -> IEnumerable<TSource>

Returns distinct elements from a sequence by using the default equality comparer.

Parameters

NameTypeDescription
sourceIEnumerable<TSource>Sequence to remove duplicates from.

Returns

IEnumerable<TSource>

Example

csharp
int[] nums = { 1, 2, 2, 3, 3, 3 };
var unique = nums.Distinct();
// unique == [1, 2, 3]