Working with Data

Sorting

Method NameDescriptionC# Query Expression Syntax

OrderBy

Sorts values in ascending order.

orderby

OrderByDescending

Sorts values in descending order.

orderby … descending

ThenBy

Performs a secondary sort in ascending order.

orderby …, …

ThenByDescending

Performs a secondary sort in descending order.

orderby …, … descending

Reverse

Reverses the order of the elements in a collection.

NA

string[] words = {"the", "quick", "brown", "fox", "jumps"};

IEnumerable<string> queryStx =
	from word in words
	orderby word.Length
	select word;

IEnumerable<string> methodStx = words.OrderBy(w => w.Length);

foreach (string str in queryStx)
	Console.Write(str + " ");

/* Output : the fox quick brown jumps */

Filtering

Method NameDescriptionC# Query Expression Syntax

OfType

Selects values, depending on their ability to be cast to a specified type.

NA

Where

Selects values that are based on a predicate function.

where

string[] words = {"the", "quick", "brown", "fox", "jumps"};

IEnumerable<string> queryStx =
	from word in words
	where word.Length == 3
	select word;

IEnumerable<string> methodStx = words.Where(w => w.Length == 3);

foreach (string str in methodStx)
	Console.Write(str + " "); 

/* Output: the fox */

Partitioning

Method namesDescription

Skip

Skips elements up to a specified position in a sequence.

SkipWhile

Skips elements based on a predicate function until an element does not satisfy the condition.

Take

Takes elements up to a specified position in a sequence.

TakeWhile

Takes elements based on a predicate function until an element does not satisfy the condition.

Chunk

Splits the elements of a sequence into chunks of a specified maximum size.

int[] numbers = {5, 9, 7, 2, 4, 3, 6, 1, 8};
foreach (var num in numbers.Take(3)) {
	Console.Write(num + "\t");
} /* Output : 5    9    7 */
foreach (var num in numbers.Skip(3)) {
	Console.Write(num + "\t");
} /* Output : 2    4    3    6    1    8 */
int chunkNumber = 1;
foreach (int[] chunk in Enumerable.Range(0, 9).Chunk(3)) {
	Console.Write($"Chunk {chunkNumber++}:");
	foreach (int item in chunk) {
		Console.Write($"    {item}");
	}

	Console.WriteLine();
}
// Output:
// Chunk 1:    0    1    2
// Chunk 2:    3    4    5
// Chunk 3:    6    7    8

Grouping

Method NameDescriptionC# Query Expression Syntax

GroupBy

Groups elements that share a common attribute. Each group is represented by an IGrouping<TKey,TElement> object.

group … by -or- group … by … into …

ToLookup

Inserts elements into a Lookup<TKey,TElement> (a one-to-many dictionary) based on a key selector function.

NA

List<int> numbers = new List<int>(){35, 44, 200, 84, 3987, 4, 199, 329, 446, 208};
IEnumerable<IGrouping<int, int>> query =
	from number in numbers
	group number by number % 2;
	
foreach (var group in query) {
	Console.Write(group.Key == 0 ? "\nEven numbers: " : "\nOdd numbers: ");
	foreach (int i in group)
		Console.Write(i + " ");
}

Last updated