Extension methods for Enumerables

Mapping

Map<T, TResult>(Func<T, TResult> selector)

Projects each element of a sequence into a new form. This method is a synonym for Aggregate.

IEnumerable<int> doubledElements = source.Map(n => 2 * n);

Replace<T>(Func<T, bool> predicate, T replacement)

Replaces every element that matches a given predicate to another element.

int[] numbers = new [] { 2, -5, 0, 1, -7, 3 };
var trimmed = numbers.Replace(n => n < 0, 0); // 2, 0, 0, 1, 0, 3

Replace<T>(T subject, T replacement)

Replaces every occurrences of subject to replacement.

string[] words = new [] { "Blue", "is", "my", "favorite", "color" };
IEnumerable<string> result = words.Replace("Blue", "Red"); 

Replace<T, TResult>(IDictionary<T, TResult> map)

Replaces elements based on a map.

string plaintext = "HELLO WORLD";
IDictionary<char, char> map = new Dictionary<char, char>() {
	{ 'A', 'K' },
	{ 'B', 'E' },
	{ 'C', 'Y' },
	// ...
};
IEnumerable<char> ciphertext = plaintext.Replace(map); 

Order

CycleBackward<T>(int offset = 1)

Cycles the elements of a sequence backward by a given offset.

CycleForward<T>(int offset = 1)

Cycles the elements of a sequence forward by a given offset.

string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string caesarsAlphabet = alphabet.CycleForward(3);

Shuffle<T>()

Returns elements in a random order.

IEnumerabe<Card> deck = Deck.Create().Shuffle();

Set operations

Except<T>(Func<T, bool> predicate)

Filters elements based on a predicate.

int[] numbers = new int[] { 1, -4, 2, -3, 5 };
var onlyIntegers = numbers.Except(n => n < 0);

IsSubsetOf<T>(IEnumerable<T> second, bool strict = false)

Determines whether the specified set is a subset of this set.

bool result = new [] { 1, 2, 3 }.IsSubsetOf(new [] { 1, 2, 3, 4, 5 });

IsSupersetOf<T>(IEnumerable<T> second, bool strict = false)

Determines whether the specified set is a superset of this set.

bool result = new [] { 1, 2, 3, 4, 5 }.IsSupersetOf(new [] { 1, 2, 3 });

SetEqual<T>(IEnumerable<T> second)

Determines whether the two sets contain the same elements.

bool result = new [] { 1, 2, 3, 4 }.SetEqual(new [] { 3, 1, 2, 4 });

Searching

ElementAtMax<T, TSelector>(Func<T, TSelector> selector)

Returns the element that yields the maximum value using a selector function.

string input = "This is a sample sentence.";
char top = candidate.GroupBy(c => c).ElementAtMax(g => g.Count()).Key;

ElementAtMin<T, TSelector>(Func<T, TSelector> selector)

Returns the element that yields the minimum value using a selector function.

IndexOf<T>(T element, int startIndex = 0)

Reports the zero-based index of the first occurrence of the specified element.

int[] numbers = new int[] { 1, 4, 1, 5, 9, 2, 6, 5 };
int positionOfTwo = numbers.IndexOf(2);

IndexOfAny<T>(T element, IEnumerable<T> anyOf, int startIndex = 0)

Reports the zero-based index of the first occurrence of any of specified elements.

int[] numbers = new int[] { 1, 4, 1, 5, 9, 2, 6, 5 };
int positionOfTwoOrFive = numbers.IndexOf(new [] { 2, 5 });

Subsequences

Skip<T>(int startIndex, int count)

Bypasses a specified number of elements from a given position and returns the remaining elements.

SkipEvery<T>(int n)

Skips every nth element of the sequence.

Split<T>(int size)

Splits a sequence into parts with a specified length.

Split<T>(T separator)

Splits a sequence into parts by a specified separator.

char[] characters = new char[] { '1', ',', '2', ',', '3', '4' };
var digitsOfNumbers = characters.Split(',');

StarsWith<T>(IEnumerable<T> second)

StarsWith<T>(IEnumerable<T> second, IEqualityComparer<T> comparer)

Determines whether the start of the sequence matches the specified sequence using the specified equality comparer.

bool result = new [] { 1, 2, 3, 4, 5 }.StartsWith(new [] { 1, 2, 3 });

EndsWith<T>(IEnumerable<T> second)

EndsWith<T>(IEnumerable<T> second, IEqualityComparer<T> comparer)

Determines whether the end of the sequence matches the specified sequence using the specified equality comparer.

Subsequence<T>(int startIndex, int count)

Retrieves a subsequence from a sequence. The subsequence starts at a specified position and has a specified length.

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
var result = numbers.Subsequence(1, 3); // 2 3 4

Take<T>(IEnumerable<int> indexes)

Takes elements at specified indexes.

TakeEvery<T>(int n)

Takes every nth element of the sequence.

Folding

Apply<T, TResult>(Func<IEnumerable<T>, IEnumerable<TResult>> transform)

Applies a specified transform on the sequence.

BinaryFold<T>(Func<T, T, T> accumulator)

Makes pairs of consecutive elements and folds every pair into a new element.

BinaryFoldRecursive<T>(Func<T, T, T> accumulator)

Makes pairs of consecutive elements and folds every pair into a new element recursively until only one single element remains.

Differentiate<T, TResult>(Func<T, T, TResult> accumulator)

Folds every consecutive two elements to a new one.

double[] results = new double[] { 2.3, -1.2, 0.1, 3.05, -0.6 };
IEnumerable<double> differences = results.Differentiate((x, y) => y - x);

Fold<T>(Func<T, T, T> accumulator)

Applies an accumulator function over a sequence. This method is a synonym for Aggregate.

Fold<T, TResult>(TResult seed, Func<TResult, T, TResult> accumulator)

Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value.

Fold<T, TResult>(Func<IEnumerable<T>, TResult> accumulator)

Folds all the elements into a single element.

MapReduce<S, M, K, R>(Func<S, IEnumerable<M>> mapper, Func<M, K> keySelector, Func<K, IEnumerable<M>, R> reducer)

Executes a map and a reduction function on the sequence.

Unfold<T>(Func<IList<T>, T> generator)

Unfolds this sequence to another sequence using a generator function.

IEnumerable<int> fibonacci = new int[] { 0, 1 }.Unfold(
	elements => elements[elements.Length - 2] + elements[elements.Length - 1]
);

Combining

Combine<T1, T2, TResult>(IEnumerable<T2> second, Func<T1, T2, TResult> resultSelector)

Merges two sequences by using the specified predicate function.

int[] first = new int[] { 1, 2, 3 };
int[] second = new int[] { 4, 5, 6 };

int[] sum = first.Combine(second, (x, y) => x + y);

Actions

ForEach<T>(Action<T> action)

Executes a given action on every element of an enumerable.

Enumerable.Range(1, 10).ForEach(Console.WriteLine);

ForEach<T>(IEnumerable<Action<T>> actions)

Executes the corresponding action on every element.

Miscellaneous

Separate<T>(T separator)

Adds a specified separator between each element.

string[] words = new string[] { "My", "favorite", "color", "is", "blue" };
IEnumerable<string> wordList = words.Separate(",");

Last edited Nov 17, 2012 at 8:05 PM by BlueCode, version 9

Comments

No comments yet.