C# – Enumerable Methods

C# – LINQ Enumerable Methods

Link to Microsoft Docs: Here

Aggregate
– Iterates over the elements in a sequence and aggregates them using the specified aggregate function.
– Aggregate function takes in 2 arguments: seed and function
Sample Code
All
– Whether all elements in the collection match a certain predicate
– Returns Boolean result
– Returns true if and only if there is not an item in the list that fails to match the predicate condition
– Empty collection will return true
Sample Code
Any
– Determines any element in the sequence matches the predicate
– Returns Boolean result
– Parameters IEnumerable
– It uses early-exit once it meets its predicate

public static bool Any<TSource&gt(this IEnumerable<TSource&gt source) {
            if (source == null) throw Error.ArgumentNull("source");
            using (IEnumerator<TSource&gt e = source.GetEnumerator()) {
                if (e.MoveNext()) return true;
            }
            return false;
        }
public static bool Any<TSource&gt(this IEnumerable<TSource&gt source, Func<TSource, bool&gt predicate) {
            if (source == null) throw Error.ArgumentNull("source");
            if (predicate == null) throw Error.ArgumentNull("predicate");
            foreach (TSource element in source) {
                if (predicate(element)) return true;
            }
            return false;

}
Sample Code

Append
Refer to Concat method
AsEnumerable
– Generic interface which defines a template for looping, allows to cast a specific type. You can access it through queries or for-each loop.
– It helps to execute part of the query in memory.
Table.Where(predicate) => query executed at SQL Server level
Table.AsEnumerable().Where(predicate) => query executed in memory

Table.Where(somePredicate)
     .Select(someProjection)
     .AsEnumerable()
     .SomethingElse()

Reference
Sample Code

Average
– Calculates the average of the sequence of numeric values, returns single average result, it is an extension method.
Sample Code
Cast
– Attempts to cast each item in the collection. Only performs cast and not cast conversion For example cast conversion from object to long will throw InvalidCastException.
– You can cast to base class but not the opposite.
– Useful when converting IEnumerable to an IEnumerable <T>
Sample Code
Concat
– Concatenates two sequences.
– Two parameters of type IEnumerable and returns concatenated elements of the two inputs of type IEnumerable.
– Can combine Lists, Arrays or IEnumerables together.
– For adding List for performance it is better to use AddRange.
Sample Code
Contains
– Search for the specific element in the sequence.
– Parameters are source IEnumerable and value and returns boolean result.
– Terminated once the matched value is found.
– Extension method can be called on collections such as arrays, lists, etc.
– It has both extension and List method.
– Contains extension method can be called on any type that implements IEnumerable.
Sample Code
Count ?
– Returns the number of elements in a sequence.
– Takes IEnumerable as parameter and returns int in result.
– Not very useful as it always acts upon List and arrays when they have other properties such as count and length.
– Count() is only effective when used with LINQ query expression.
– Count can take argument such as Lambda expression, where count only elements that meets the condition
Sample Code
DefaultIfEmpty
– returns default value instead of error. Used to replace empty collection with a default value of singleton collection
– you can pass parameter or no parameter
– can only be used to handle empty collection
List list = new List();
var result = list.DefaultIfEmpty(); // will return 0
result = list.DefaultIfEmpty(1); // will return 1

Sample Code
Distinct
– Returns distinct elements from a sequence and removes all the duplicates.
– Parameter as IEnumerable and returns IEnumerable collection which can be iterated.
– Heap allocations occur when you invoke Distinct, for better performance you can use loops.
Sample Code
ElementAt ?
– Returns the element at a specified index in a sequence.
– Parameters IEnumerable and Int32 zero-based index.
– In many IEnumerable types, you cannot directly index a certain element.
– It is better to use indexer for string for better performance. eg string[99] rather than string.ElementAt(99).
– If a collection has indexer then don’t use ElementAt().
– Can be used for Queue or Stack but it is not a best practice instead try to convert stacks and queue into array or list and use the indexer.
Sample Code
ElementAtOrDefault
– Returns the element at a specified index in a sequence or a default value if the index is out of range.
– It handles out-of-range access without throwing an exception.
– Parameters IEnumerable and Int32 zero-based index.
– Returns element at the specified position or default value.
Sample Code
Empty
– Returns an empty IEnumerable(Of T) that has the specified type argument.
– When you want to create an empty sequence.
– Type of the sequence declaration is important.
– It has performance advantage because it caches zero element array compared to empty array initialization.
Sample Code
Except
– Returns a difference from the two sequences, basically subtracts elements from the collection.
– The elements of second sequence is subtracted from the first sequence.
– Elements found in second sequence not available in first will be ignored.
Sample Code
First
– Returns the first matching object from the sequence if predicate is used or first item from the object.
– Parameter takes in as IEnumerable collection.
– Throws exception if not result found or empty collection
Sample Code
FirstOrDefault
– Returns either first element of a sequence or first element of the sequence that satisfies a condition, or a default value if the sequence contains no elements.
Sample Code
GroupBy
– Transforms the sequence into groups where each group has a key.
– For performance optimization it is better to use ToDictionary if it is used randomly.
– Also List can be used if it contains multiple elements (Dictinary of Lists).
Sample Code
GroupJoin
– Correlates the elements of two sequences based on key equality, and groups the results.
– It requires 4 arguements: secondary collection, function returns key from first object, function return key from 2nd object and last one that stores group data.
– Alternative solution will be to use Dictionary and implementing IEqualityComparer.
Sample Code
Intersect
– Returns a set of common results found from both collections.
Sample code
Join
– Matches every element in two sequences based on matching keys.
– Parameters: first sequence to join as outer parameter, then inner params – sequence to join the first sequence, outer sequence key to join each element, key for the second sequence and function to create the result from the matching result.
Sample Code
Last
– Returns the last element from the sequence to that matches the predicate in the sequence.
– Parameter – it takes sequence as the parameter and returns the last element from the sequence or last element that matches the condition.
Sample Code
LastOrDefault
– It returns the last element in the sequence or the default value.
– It also returns the last element of the sequence that matches a condition or default value. Parameter – it takes sequence as the parameter and returns the last element from the sequence or last element that matches the condition otherwise default value.
Sample Code
LongCount
– Returns an Int64 that represents the total number of elements in a collection.
– Use this method rather than Count when you expect the result to be greater than MaxValue.
– Also returns an Int64 that represents how many elements in a sequence match a condition.
Sample Code
Max
– Loops through the sequence and returns the highest value.
– The max 22 overload with different data-types Decimal, Double, Int32, Int64 and Single, and nullable versions of each of these.
– These methods are most useful with a lambda expression. Cannot be called on empty collection throws an exception.
Sample Code
Min
– Loops through the sequence and returns the smalled value.
– The max 22 overload with different data-types Decimal, Double, Int32, Int64 and Single, and nullable versions of each of these.
– These methods are most useful with a lambda expression. Cannot be called on empty collection throws an exception.
Sample Code
OfType
– Gets all the elements by their matching type in the collection (IEnumerable).
– It provides a useful way to query for elements of a certain type.
Sample Code
OrderBy
– Identifies how the sequence should be arranged.
– It can be invoked to any sequence that implements IEnumerable.
– It is better to use OrderBy when compared with generic Sort function.
– Parameter IEnumerable collection and function to extract key from collection and IComparer to compare keys.
Sample Code
OrderByDescending
– Sorts the element in the collection from higest to lowest.
– It uses the lambda expression to select the key for sorting.
– Sorts the elements of a sequence in ascending/descending order by using a specified comparer.
Sample Code
Prepend
– use Concat instead, not enough information provided here.
Range
– Takes the parameter as start and count and then it generates the sequence on integral numbers in progressing order within a specified range.
– The second argument needs to be greater than zero, will throw exception if it is negative.
Sample Code
Repeat
– Takes in the parameter as element and count – repeated number of times and then it generates a sequence that contains one repeated value.
– IEnumerable result can be converted into ToArray() or ToList() to assign array or list.
Sample Code
Reverse
– Inverts the order of the elements in a collection (opposite), can be used with many collection types such as lists, array, IEnumerable.
– As for performance it is not the best practice, alternative approach is to use array.reverse or use loops.
– It is shortcut to use but not so good in performance.
Sample Code
Select
1) Modify each element in a collection into a new form
2) Modify each element into a new form by incorporating the element’s index.
– It can be applied on different collection types such as List.
Sample Code
SelectMany
1) Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.
2) Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.
3) Projects each element of a sequence to an IEnumerable, and flattens the resulting sequences into one sequence. The index of each source element is used in the projected form of that element.
4) Projects each element of a sequence to an IEnumerable, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein.
5) Projects each element of a sequence to an IEnumerable, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein. The index of each source element is used in the intermediate projected form of that element.
– Can change the element into an array or collection.
Sample Code
SequenceEqual
1) Determines whether two collections are equal by comparing the elements by using the default equality comparer for their type.
2) Determines whether two collections are equal by comparing their elements by using a specified IEqualityComparer.
– Testing two collections for equality.
– If using arrays consider using ArraysEquals for performance optimization.
Sample Code
Single
1) Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
2) Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.
– Best used as runtime assert to throw errors.
Sample Code
SingleOrDefault
1) Returns the only element of a sequence, or a default value if the sequence is empty. This method throws an exception if there is more than one element in the sequence.
2) Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists. This method throws an exception if more than one element satisfies the condition.

var parentClaim = bl.Get(childClaimId: claimId)
                    .SingleOrDefault(x => x.ClaimRelationshipTypeId == reversalTypeId || x.ClaimRelationshipTypeId == reissueTypeId);

Sample Code

Skip
– Disregards the specified number of elements in the sequence and returns the remaining.
– No result will be visible unless you iterate using loop to view the collection data.
– You can use Take with Skip.
Sample Code
SkipLast
– Not enough information
SkipWhile
– Disregards the elements in the collection as long as predicate is true and returns the remaining elements in the collection.
– You will need to specify a predicate condition inorder to skip values.
– You can convert into ToArray to ToList to convert the IEnumerable back into an array or List.
Sample Code
Sum
– Calculates the sum of a collection of numeric values.
– There are 20 overloads for the data-types Decimal, Double, Int32, Int64 and Single, and nullable versions of each of these.
Sample Code
Take
– Returns the specified first several number of elements from the collection.
– Returns another collection of result.
– Receives parameter as element count.
– If parameter count exceeds with the number of elements in a collection, take will handle without any problem.
– You can use Take with Skip
Sample Code
TakeLast
– Not enough information, consider reversing the list and use take() method.
TakeWhile
– Returns the elements in the sequence while it matches the predicate.
– It precedes from the beginning of the collection.
Sample Code
ThenBy
– Orders the collection in ascending order
Sample Code
ThenByDescending
– Orders the collection in descending order
Sample Code
ToArray
– Converts collections into Arrays specially IEnumerable types.
– Reduces complexity and program length
– You can append the ToArray method to the query to obtain a cached copy of the query results.
Sample Code
ToDictionary
– Converts a sequence into a Dictionary.
– Applicable to IEnumerable collections such as arrays and Lists.
– It can optimize performance rather then using generic collections.
– Parameter: first set each key and second set each value.
Sample Code
ToHashSet
– Not enough information
ToList
– Creates a List from a set of collections with List constructor.
Sample Code
ToLookup
– Returns ILookup that allows indexing and iteration.
– It allows one key to be associated with multiple values.
Sample Code
Union
– Produces a new set of collections from joining 2 sets of collections.
– It removes duplicates to the collection
– The two collections needs to be same type
– Mostly works on Lists and Arrays
– Results are not sorted in union
– Alternative method could be hash table or dictionary but will not remove duplicates
Sample Code
Where
– Filters values based on the predicates and returns all the matched results
– Mostly used in queries
var results = bl.Get(parentClaimId: claimId)
.Where(x => x.ClaimRelationshipTypeId == reversalTypeId || x.ClaimRelationshipTypeId == reissueTypeId);

Sample Code
Zip
– Uses two collections and processes each element from both collections together.
– Zip will not throw an exception if the two collections are of unequal length.
Sample Code

Finally completed learning with LINQ Enumerable methods. My learning resource and examples are based from msdn, dreamincode and dotnetpearl. Thanks for the awesome articles.

Feel free to contact me if you have any concerns.

Live as if you were to die tomorrow. Learn as if you were to live forever..
-Mahatma Gandhi