Monthly Archives: August 2015

Helpful LINQ Extensions

Iterator.cs:

public class Iterator<T>
{
    public T Value { get; private set; }
    public int Index { get; private set; }

    public Iterator(T value, int index)
    {
        Value = value;
        Index = index;
    }
}

EnumerableExtensions.cs:

using System.Collections.Generic;
using System.Linq;

public static class EnumerableExtensions
{
    public static IEnumerable<T> Yield<T>(T item)
    {
        yield return item;
    }

    public static IEnumerable<T> Append<T>(this IEnumerable<T> @this, T item)
    {
        foreach (T existingItem in @this)
        {
            yield return existingItem;
        }
        yield return item;
    }

    public static IEnumerable<T> Prepend<T>(this IEnumerable<T> @this, T item)
    {
        yield return item;
        foreach (T existingItem in @this)
        {
            yield return existingItem;
        }
    }

    public static IEnumerable<Iterator<T>> Iterate<T>(this IEnumerable<T> @this)
    {
        return @this.Select((value, index) => new Iterator<T>(value, index));
    }
}

User-Friendly Names for Enumerations

EnumExtensions.cs:

using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

public static class EnumExtensions
{
    public static string ToDescription(Enum value)
    {
        FieldInfo field = value.GetType().GetField(value.ToString());
        DescriptionAttribute attribute = field.GetCustomAttribute<DescriptionAttribute>();
        return attribute.Description;
    }

    public static TEnum FromDescription<TEnum>(string description)
    {
        return (TEnum)typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
            .Single(field => field.GetCustomAttribute<DescriptionAttribute>().Description == description)
            .GetValue(null);
    }
}

Stock.cs:

using System.ComponentModel;

public enum Stock
{
    [Description("General Electric")]
    GE,

    [Description("Exxon Mobil Corporation")]
    XOM,

    [Description("Merck & Company")]
    MRK,

    [Description("Citigroup, Inc.")]
    C,

    [Description("Wal-Mart Stores")]
    WMT
}

Program.cs:

using System;

internal static class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Stocks:");
        foreach (Stock stock in Enum.GetValues(typeof(Stock)))
        {
            Console.WriteLine("    {0}", EnumExtensions.ToDescription(stock));
        }
        Console.Write("Enter stock: ");
        string description = Console.ReadLine();
        Console.WriteLine("This stock's symbol is {0}.", EnumExtensions.FromDescription<Stock>(description));
    }
}

Output:

Stocks:
    General Electric
    Exxon Mobil Corporation
    Merck & Company
    Citigroup, Inc.
    Wal-Mart Stores
Enter stock: General Electric
This stock's symbol is GE.