All C# extension methods for type ienumerable-t
-
WhereIf
When building a LINQ query, you may need to involve optional filtering criteria. Avoids if statements when building predicates & lambdas for a query. Useful when you don't know at compile time whether a filter should apply. Borrowed from Andrew Robinson. http://bit.ly/1V36G9
-
OrderBy(string sortExpression)
Orders a list based on a sortexpression. Useful in object databinding scenarios where the objectdatasource generates a dynamic sortexpression (example: "Name desc") that specifies the property of the object sort on.
-
ForEach
Shortcut for foreach and create new list
-
Pivot
Groups the elements of a sequence according to a specified firstKey selector function and rotates the unique values from the secondKey selector function into multiple values in the output, and performs aggregations.
-
ToDataTable
Converts an IEnumerable to DataTable (supports nullable types) adapted from http://www.c-sharpcorner.com/UploadFile/VIMAL.LAKHERA/LINQResultsetToDatatable06242008042629AM/LINQResultsetToDatatable.aspx
-
ToObservableCollection<T>()
Convert a IEnumerable<T> to a ObservableCollection<T> and can be used in XAML (Silverlight and WPF) projects
-
IsNotNullOrEmpty
It returns false if given collection is null or empty otherwise it returns true.
-
Randomize
OrderBy() is nice when you want a consistent & predictable ordering. This method is NOT THAT! Randomize() - Use this extension method when you want a different or random order every time! Useful when ordering a list of things for display to give each a fair chance of landing at the top or bottom on each hit. {customers, support techs, or even use as a randomizer for your lottery ;) }
-
ForEach
Shortcut for foreach
-
IndexOf<T>()
Returns the index of the first occurrence in a sequence by using the default equality comparer or a specified one.
-
ToCSV
An extension method that produce a comman separated values of string out of an IEnumerable<T>. This would be useful if you want to automatically generate a CSV out of integer, string, or any other primative data type collection or array. I provided 2 overloads of this method. One of them accepts a separator and the other uses comma "," as default separator. Also I am using another shortcut extension method for foreach loop.
-
ToCollection<T>()
Convert a IEnumerable<T> to a Collection<T>
-
Shuffle
Shuffles an IEnumerable list
-
OrderBy
OrderBy is nice, except if you want to sort by multiple properties or want an easy way to distinguish between ascending and descending.
-
Slice<T>(int start, int end)
Returns the range of elements between the specified start and end indexes. Negative numbers count from the end, rather than the start, of the sequence. Values of 'end' larger than the actual sequence are truncated and do not cause index-out-of-bounds exceptions. Functionally very similar to Python's list[x:y] slices.
-
Transpose
transposes the rows and columns of its argument
-
Distinct
Provides a Distinct method that takes a key selector lambda as parameter. The .net framework only provides a Distinct method that takes an instance of an implementation of IEqualityComparer<T> where the standard parameterless Distinct that uses the default equality comparer doesn't suffice.
-
ToHashSet<T>
Takes any IEnumerable<T> and converts it to a HashSet<T>
-
Each<T>
iterates through an IEnumerable<T> and applies an Action
-
ToString
Concatenates a specified separator String between each element of a specified enumeration, yielding a single concatenated string.
-
Cache()
Caches the results of an IEnumerable.
-
Split
somtimes one needs to split a larger collection into multiple smaller ones, this one does so use deferred execution
-
TakeUntil
The opposite of TakeWhile, inverts the expression and passes to TakeWhile so that instead of taking while an expression is true, you take until an expression is true.
-
FirstOrNull
Returns the null when there's null first element in the sequence instead of throwing an exception
-
SelectRandom
This method selects a random element from an Enumerable with only one pass (O(N) complexity). It contains optimizations for argumens that implement ICollection<T> by using the Count property and the ElementAt LINQ method. The ElementAt LINQ method itself contains optimizations for IList<T>
-
Filter
Allows you to filter an IEnumerable<T>
-
Combinations
Returns all combinations of a chosen amount of selected elements in the sequence.
-
IsNullOrEmpty
Determines whether a collection is null or has no elements without having to enumerate the entire collection to get a count.
-
Aggregate
Since System.Linq.Enumerable.Aggregate throws a System.InvalidOperationException in case the given list is empty you can't use this function in a complex linq expression. This aggregate version simply returns a defaultvalue if the list is empty
-
Async
Starts execution of IQueryable on a ThreadPool thread and returns immediately with a "end" method to call once the result is needed.
-
Slice of IEnumerable
Returns count elements, beginning from the specified
-
Reverse
Reverses the order of the list that you wish to enumerate.
-
ToCsv
Returns a string that represent a csv representation of the referenced T in the IEnumerable<T>. You can also generate a columns header (the first row) with the name of the serialized properties. You can specify the name of the properties to include in the csv file. If you don't specify anything it will includes all the public properties.
-
Concat
Adds an element to an IEnumerable (System.Linq.Concat only adds multiple elements)
-
ToHtmlTable
Converts an IEnumberable<T> to an HTML DataTable.
-
Zip
Merges three sequences by using the specified predicate function.
-
FirstIndex() and LastIndex()
Finds the index of the first of last occurence which matches the predicate.
-
GetPermutations
GetPermutations
-
None(), OneOf(), Many(), XOf()
Count-based extensions which make checking the length of something more readable. * Updated on 2010-01-16 following suggestion from @Sane regarding the use of Count() in None(). Switched to Any(). Thanks!
-
IsNullOrEmpty
Check whether a collection is null or doesn't contain any elements.
-
IndexOf
Gets the index of the give value in a collection. Is overloaded to take a start parameter as well.
-
IsSingle
Determines whether the collection has exactly one element
-
WriteToConsole
Write all elements in the Enumeration to the Console
-
Convert
Converts from one type to another.
-
Sort algorithms
This is a set of extesion methods that sort a given list more about that on codeplex
-
CountOf
Returns whether the sequence contains a certain amount of elements, without having to traverse the entire collection.
-
IsNullOrEmpty
Checks if the collection is null or empty
-
ForEach
Foreach inline for the IEnumerable<T>.
-
DefaultIfEmpty
The provided DefaultIfEmpty will only accept an instance of T as the default value. Sometimes you need the default to be an IEnumerable<T>.
-
join
--
-
FindMin() and FindMax()
Selects the object in a list with the minimum or maximum value on a particular property
-
CloneExplicit<T>
Creates an explicit copy of the given enumerable where the only values copied are the ones you designate.
-
SplitUp()
This SplitUp() extension method takes a sequence and splits it up into subsequences that each have a maximum length. See http://peshir.blogspot.nl/2011/02/example-of-c-lazy-functional.html for more information.
-
IndicesOf
Finds all the indexes of the give value or values in an enumerable list
-
bool IsSorted (Comparison<T> comparison)
returns true if a sequence is sorted
-
ToObservableCollection<T>()
Convert a IEnumerable<T> to a ObservableCollection<T> and can be used in XAML (WPF, Silverlight, Windows Phone & Windows Store) projects
-
SkipLast
take all but the last item from an IEnumerable<T>
-
Product
Computes a product of all elements in the sequence.
-
ConcatTo
Adds a single element at the beginning of an enumerator
-
CacheGeneratedResults
Caches the results of generator methods so that expensive enumerations are not repeated if they are enumerated multiple times. Yet it caches the results lazily, allowing for memory efficiency where possible.
-
ToObservableCollection
Copies elements from IEnumerable<T> into ObservableCollection<T>. Handy for converting LINQ results into a list appropriate for WPF databinding.
-
RandomElements
Returns a number of random elements from a collection
-
Convert
Converts all elements in an enumerable list from the its to a destination type by calling a provided conversion function
-
WrapEachWithTag
Creates a string that is each the elements' ToString() values wrapped in the 'tag' that is passed as a param. Good for converting an IEnum<T> into a block of HTML/XML.
-
Cycle
Repeats a sequence forever.
-
ThrowIfAny
Throws a given exception is any value in a set passes a given predicate
-
In
Filters a list based on a comma-separated list of allowed values. This is a lot more concise than using a number of 'or' clauses
-
Each
Iterates over all the elements in a collection and performs the given action, usually given as a lambda.
-
Randomize
Randomizes am IEnumerable<T>
-
WhereNotNull
I’m a big fan of the Nullable Reference Types feature added in C# 8.0. It lets the compiler catch a bunch of potential runtime errors, and I guarantee if you turn it on you’ll get a bunch of warnings. As of .NET 5.0, the entire BCL is now covered with nullable annotations, and a lot of the extended ecosystem supports them too. But there are situations where the compiler is unable to work out that you’ve done a null check, meaning you either have to use the “null-forgiving operator” (where you append a bang to the identifier, like item!.Name), disable the null checking, or just ignore the warning. The WhereNotNull extension method filters out nulls and changes the expression type accordingly. source: https://rendle.dev/posts/where-not-null/
-
In
Determines whether a variable of type T is contained in the supplied list of arguments of type T, allowing for more concise code.
-
ToList(capacity)
LINQ ToList() extension method with an extra capacity argument. This can boost the speed of creating the list.
-
WherePrevious
Compare Through a predicate every element of a list with the previous one
-
Cached
Cache result of IEnumerable iteration. Similar to other implemetations with two advantages: 1 - Not flawed (Dispose of IEnumerator done by compiler) 2- Simplier
-
AsNullSafeEnumerable
You don't need check whether the collection is null.
-
Follow
Follows sequence with new element
-
Penultimate
Gets the penultimate item of a collection
-
FillSpan
Fill any Span using an IEnumerable. Returns the number of items which are placed in the Span.
-
FastSum
Sum decimals
-
TryGetNonEnumeratedCount
Attempts to determine the number of elements in a sequence without forcing an enumeration. For those who are not yet using .NET 6
-
AnyAndAll
Determines whether a sequence contains any elements and whether all elements of a sequence satisfy a condition. The normal 'All' method returns true when the sequence is empty.
-
EnumerateWithIndex<T>()
Enumerate an IEnumerable<T> source and getting the Index and the Item returned in a ValueTuple.
-
SkipFrom
Bypasses a specified number of elements in a sequence from a given start position