Extension Methods Roundup: Intersect, Union, AsNullable and GroupEvery

1 באוגוסט 2008

אין תגובות

Here we go with the third installment of the Extension Method Roundup. The reason behind these 'code dumps' is that LINQ is a central part of my coding and always find new problems I want to find elegant solutions to. Hope these prove as useful to you as they do to me.

Intersect / Union

Again, shorthand for when you have Enumerable of Enumerable of T and you simply want to intersect or union all of the enumerations in one single call.

public static IEnumerable<T> Intersect<T>(this IEnumerable<IEnumerable<T>> enumeration)
{
    // Check to see that enumeration is not null
    if (enumeration == null)
        throw new ArgumentNullException("enumeration");

    IEnumerable<T> returnValue = null;

    foreach (var e in enumeration)
    {
        if (returnValue != null)
            returnValue = e;
        else
            returnValue = returnValue.Intersect(e);
    }

    return returnValue;
}

public static IEnumerable<T> Union<T>(this IEnumerable<IEnumerable<T>> enumeration)
{
    // Check to see that enumeration is not null
    if (enumeration == null)
        throw new ArgumentNullException("enumeration");

    IEnumerable<T> returnValue = null;

    foreach (var e in enumeration)
    {
        if (returnValue != null)
            returnValue = e;
        else
            returnValue = returnValue.Union(e);
    }

    return returnValue;
}

AsNullable

I was always missing this method, to coincide with the Cast and OfType methods.

public static IEnumerable<T?> AsNullable<T>(this IEnumerable<T> enumeration)
    where T : struct
{
    return from item in enumeration
           select new Nullable<T>(item);
}

GroupEvery

This takes count items from an enumeration and groups them into a single array.

public static IEnumerable<T[]> GroupEvery<T>(this IEnumerable<T> enumeration, int count)
{
    // Check to see that enumeration is not null
    if (enumeration == null)
        throw new ArgumentNullException("enumeration");

    if (count <= 0)
        throw new ArgumentOutOfRangeException("count");

    int current = 0;
    T[] array = new T[count];

    foreach (var item in enumeration)
    {
        array[current++] = item;

        if (current == count)
        {
            yield return array;
            current = 0;
            array = new T[count];
        }
    }

    if (current != 0)
    {
        yield return array;
    }
}

I've also gone and updated my LINQ Extensions project on CodePlex with everything I've published since the last update. You're welcome to download and fiddle with it. :)

[Cross-Posted from Omer van Kloeten's .NET Zen, my English language weblog]

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים