🔢Enumerable Utility

Summary

Extension methods that are meant to operate on any object that implements Enumerable or inherits from IEnumerable

IsNullOrEmpty

Description

Extension method that checks if the IEnumerable is null or contains 0 values

Examples

List<int> foo = new() { 0, 1, 2 };

foo.IsNullOrEmpty(); // false

EmptyIfNull

Description

Extension method that returns an empty Collection<T> if the IEnumerable is null. If the source is not null, no modification is made and the source is returned. If the source is null, an empty collection of the source type is returned.

This can be helpful when you want to ensure you are not passing a null value back from a function.

Examples

List<int> foo = new() { 0, 1, 2 };

return foo.EmptyIfNull(); // { 0, 1, 2 }

AsIReadOnlyList

Description

Extension method that will take any IEnumerable<T> and return it as an IReadOnlyList.

Examples

List<int> foo = new() { 0, 1, 2 };

return foo.AsIReadOnlyList(); // (IReadOnlyList<int>) foo

AsReadOnlyCollection

Description

Takes any IEnumerable and wraps it in a ReadOnlyCollection

Example

List<int> foo = new() { 0, 1, 2 };

return foo.AsReadOnlyCollection(); // return new ReadOnlyCollection<int>(foo);

WhereNotNull

Description

Takes any IEnumerable<T?> and returns IEnumerable<T> without null values. This can be useful when you want to ensure no null values exist in the enumerable

Examples

List<Item?> items = { item1, null, item2 };

return items.WhereNotNull(); // { item1, item2 }

LazyWhereNotNull

Description

This operates like WhereNotNull but uses yield. It takes any IEnumerable<T?> and returns IEnumerable<T> without null values. This can be useful when you want to ensure no null values exist in the enumerable

Examples

List<Item?> items = { item1, null, item2 };

return items.LazyWhereNotNull(); // { item1, item2 }

Last updated