Customer IEnuramble Extension

public static class IEnurambleExtension
{
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>
        (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    { 
        HashSet<TKey> keys = new HashSet<TKey>();

        foreach (TSource element in source)
            if (keys.Add(keySelector(element))) 
                yield return element;
    }

    public static IEnumerable<int> DistinctByReturnIndexes<TSource, TKey>
        (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        HashSet<TKey> keys = new HashSet<TKey>();
        int i = 0;
        foreach (TSource element in source)
        {
            if (!keys.Add(keySelector(element)))
                yield return i;
            i++;
        }
    }

    public static int FirstContainsWithIndex<TSource>
        (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        int i = 0;
        foreach (TSource element in source)
        {
            if (predicate(element))
                return i;
            i++;
        }

        return -1;
    }

    public static IEnumerable<int> ContainsReturnIndexes<TSource>
        (this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        int i = 0;
        foreach (TSource element in source)
        {
            if (predicate(element))
               yield return i;
            i++;
        }
    }


    public static void Print<TSource, TKey>
         (this IEnumerable<TSource> source,  Func<TSource, TKey> keySelector)
        {
            foreach (TSource element in source)
                Console.WriteLine(keySelector(element));
        }
}

 

posted @ 2014-03-07 16:50  On the road....  阅读(575)  评论(0编辑  收藏  举报