Click here to Skip to main content
Click here to Skip to main content

Few extension methods of IEnumerable in C#

By , 5 Jul 2011
 
Following are a few extension methods for IEnumerable<string>. Each extension method has a description, code and usage section to describe it.
 
public static IEnumerable<string> IfMatchWith(this IEnumerable<string> myList, string itemToMatch)
 
This extension method will iterate through the list and return those items matched with itemToMatch passed by the caller of this method.
 
public static IEnumerable<string> IfMatchWith(this IEnumerable<string> myList, string itemToMatch)
{
    foreach (var item in myList.Where(item => item == itemToMatch))
        yield return item;
}
 
Usage:
IList<string> myList = new List<string>() { "A", "B", "C", "D", "E" };
myList = myList.IfMatchWith("A").ToList<string>();
 
public static IEnumerable<string> IfNotMatchWith(this IEnumerable<string> myList, string itemToMatch)
 
This extension method will iterate through the list and return those not matched with itemToMatch passed by caller of this method.
 
public static IEnumerable<string> IfNotMatchWith(this IEnumerable<string> myList, string itemToMatch)
{
    foreach (var item in myList.Where(item => item != itemToMatch))
        yield return item;
}
 
Usage:
IList<string> myList = new List<string>() { "A", "B", "C", "D", "E" };
myList = myList.IfNotMatchWith("A").ToList<string>();
 
public static IEnumerable<string> IgnoreNullOrEmptyOrSpace(this IEnumerable<string> myList)
 
This extension method will iterate through the list and return those items only that matched with itemToMatch passed by caller of this method.
 
public static IEnumerable<string> IgnoreNullOrEmptyOrSpace(this IEnumerable<string> myList)
{
    foreach (var item in myList.Where(item => !string.IsNullOrEmpty(item) && item != " "))
        yield return item;
}
 
Usage:
IList<string> myList = new List<string>() { "A", "A", "A", "A", "", " ", "C", null };
myList = myList.IgnoreNullOrEmptyOrSpace().ToList<string>();
 
public static IEnumerable<string> MakeAllUpper(this IEnumerable<string> myList)
 
This extension method will iterate through the list and return those items after converting to upper case to the caller of this method.
 
public static IEnumerable<string> MakeAllUpper(this IEnumerable<string> myList)
{
    foreach (var item in myList)
        yield return item.ToUpper();
}
 
Usage:
IList<string> myList = new List<string>() { "A", "B", "c", "d", "E" };
myList = myList.MakeAllUpper().ToList<string>();
 
public static IEnumerable<string> MakeAllLower(this IEnumerable<string> myList)
 
This extension method will iterate through the list and return those items after converting to lower case to the caller of this method.
 
public static IEnumerable<string> MakeAllLower(this IEnumerable<string> myList)
{
    foreach (var item in myList)
        yield return item.ToLower();
}
 
Usage:
IList<string> myList = new List<string>() { "A", "B", "c", "d", "E" };
myList = myList.MakeAllLower().ToList<string>();
 
public static IEnumerable<T> MakeAllDefault<T>(this IEnumerable<T> myList)
 
This extension method will iterate through the list and return default values of those items to the caller of this method.
 
public static IEnumerable<T> MakeAllDefault<T>(this IEnumerable<T> myList)
{
    foreach (var item in myList)
        yield return default(T);
}
 
Usage:
IList<string> myList = new List<string>() { "A", "B", "c", "d", "E" };
myList = myList.MakeAllDefault<string>().ToList<string>();
 
public static IEnumerable<string> IfMatchWithPattern(this IEnumerable<string> myList, string pattern)
 
This extension method will iterate through the list and return those matched with the Pattern to the caller of this method.
 
public static IEnumerable<string> IfMatchWithPattern(this IEnumerable<string> myList, string pattern)
{
    foreach (var item in myList.Where(item => Regex.IsMatch(item, pattern)))
        yield return item;
}
 
Usage:
IList<string> myList = new List<string>() { "A", "B", "c", "d", "E" };
myList = myList.IfMatchWithPattern(".").ToList<string>();
 
public static IEnumerable<string> IfLengthEquals(this IEnumerable<string> myList, int itemLength)
 
This extension method will iterate through the list and return those items whose length is equal to the itemLength given by the caller of this method.
 
public static IEnumerable<string> IfLengthEquals(this IEnumerable<string> myList, int itemLength)
{
    foreach (var item in myList.Where(item => item.Length == itemLength))
        yield return item;
}
 
Usage:
IList<string> myList = new List<string>() { "A", "B", "c", "d", "E" };
myList = myList.IfLengthEquals(1).ToList<string>();
 
 public static IEnumerable<string> IfLengthInRange(this IEnumerable<string> myList, int startOfRange, int endOfRange)
 
This extension method will iterate through the list and return those items whose length is in range of startOfRange and endOfRange.
 
public static IEnumerable<string> IfLengthInRange(this IEnumerable<string> myList, int startOfRange, int endOfRange)
{
    foreach (var item in myList.Where(item => item.Length >= startOfRange && item.Length <= endOfRange))
        yield return item;
}
 
Usage:
IList<string> myList = new List<string>() { "A", "B", "c", "d", "E" };
myList = myList.IfLengthInRange(1, 2).ToList<string>();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Mohammad A Rahman
Software Developer
Australia Australia
Member
Designer and Architect.
Author of the Expert C# 5.0: with the .NET 4.5 Framework book

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionFrom IEnumerable(Of T) to DataTable [modified]memberRaja.Lakshman4 Apr '13 - 15:21 
Imports System.Runtime.CompilerServices
Imports System.Linq
Imports System.Reflection
 
Module IEnumerableOfTExtensions
 
    <Extension()>
    Public Function ToDataTable(Of T)(source As IEnumerable(Of T)) As DataTable
        If source Is Nothing Then
            Throw New ArgumentNullException("source")
        End If
        Dim table As DataTable = New DataTable("Generate")
        Dim first As T = source.FirstOrDefault
        If first Is Nothing Then
            Return table
        End If
        Dim properties As PropertyInfo() = first.GetType().GetProperties()
        For Each pi As PropertyInfo In properties
            If pi.PropertyType.Name.Contains("Nullable") Then
                table.Columns.Add(pi.Name, Nullable.GetUnderlyingType(pi.PropertyType))
            Else
                table.Columns.Add(pi.Name, pi.PropertyType)
            End If
        Next
        For Each t In source
            For Each pi In properties
                Dim row As DataRow = table.NewRow
                Dim obj As Object = t.GetType.InvokeMember(pi.Name, BindingFlags.GetProperty, Nothing, t, Nothing)
                If obj Is Nothing Then
                    obj = DBNull.Value
                End If
                row(pi.Name) = obj
                table.Rows.Add(row)
            Next
        Next
        Return table
    End Function
 
    <Extension()>
    Public Function ToDataTableFirstRecord(Of T)(source As IEnumerable(Of T)) As DataTable
        If source Is Nothing Then
            Throw New ArgumentNullException("source")
        End If
        Dim table As DataTable = New DataTable("Generate")
        Dim first As T = source.FirstOrDefault
        If first Is Nothing Then
            Return table
        End If
        Dim properties As PropertyInfo() = first.GetType().GetProperties()
        For Each pi As PropertyInfo In properties
            If pi.PropertyType.Name.Contains("Nullable") Then
                table.Columns.Add(pi.Name, Nullable.GetUnderlyingType(pi.PropertyType))
            Else
                table.Columns.Add(pi.Name, pi.PropertyType)
            End If
        Next
        For Each pi In properties
            Dim row As DataRow = table.NewRow
            Dim obj As Object = first.GetType.InvokeMember(pi.Name, BindingFlags.GetProperty, Nothing, first, Nothing)
            If obj Is Nothing Then
                obj = DBNull.Value
            End If
            row(pi.Name) = obj
            table.Rows.Add(row)
        Next
        Return table
    End Function
 
    Public Function ForEach(Of T)(source As IEnumerable(Of T), action As Action(Of T)) As IEnumerable(Of T)
        If source Is Nothing Then
            Throw New ArgumentNullException("source")
        End If
        If action Is Nothing Then
            Throw New ArgumentNullException("action")
        End If
        For Each item In source
            action(item)
        Next
        Return source
    End Function
 
End Module
Raja Lakshman


modified 9 Apr '13 - 21:58.

GeneralReason for my vote of 1 The methods are redundant and easily...memberDaniel Gidman20 Jul '11 - 7:36 
Reason for my vote of 1
The methods are redundant and easily implemented with Where(), Select() and other extension methods very quickly. Also you are typing the method against a string when you could easily type it against a variable type "T" such that the same methods will work across any like types.
GeneralReason for my vote of 1 Some of these methods make little se...membertitogarcia11 Jul '11 - 22:47 
Reason for my vote of 1
Some of these methods make little sense. IfMatchWith, MakeAllDefault???
In every case, why having these if their implementation is direct using Where?
Why are they implemented iterating an IEnumerable, and not just returning it?
GeneralRe: Thanks for your comment. memberMohammad A Rahman12 Jul '11 - 0:10 
Thanks for your comment.

GeneralConsider using item.IsNullOrWhiteSpace in IgnoreNullOrEmptyO...membercerda6 Jul '11 - 19:40 
Consider using item.IsNullOrWhiteSpace in IgnoreNullOrEmptyOrSpace method for sequence of spaces ...
GeneralRe: Thanks for your opinion. I will update. :)memberMohammad A Rahman6 Jul '11 - 20:29 
Thanks for your opinion. I will update. Smile | :)
GeneralShouldn't the IfLengthInRange extension method use the && op...memberGeorge Swan4 Jul '11 - 23:24 
Shouldn't the IfLengthInRange extension method use the && operator and not the || ?
GeneralRe: Thanks for that :) You are right. I will update that. memberMohammad A Rahman4 Jul '11 - 23:35 
Thanks for that Smile | :) You are right. I will update that.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 5 Jul 2011
Article Copyright 2011 by Mohammad A Rahman
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid