重构到扩展方法(1):让集合操作更方便

1. 获取数组倒数N个

 

public static IEnumerable<T> GetFromEnd<T>(this T[] array, int count)
        {
            for (int i = array.Length - 1; i > array.Length - 1 - count; i--)
            {
                yield return array[i];
            }
        }

2. Foreach集合,连续做事情。

 

public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
        {
            foreach (var item in enumerable)
            {
                action(item);
            }
            return enumerable;
        }

3. Foreach集合,有条件的做事情。

 

public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T> action, Predicate<T> condition)
        {
            foreach (var item in enumerable)
            {
                if (condition(item))
                    action(item);
            }
            return enumerable;
        }

  注意:必须return,否则无法支持链式操作,就是一直.Foreach().Foreach().Foreach()

4. For循环集合,委托返回当前索引。

 

public static IEnumerable<T> For<T>(this IEnumerable<T> enumerable, Action<int> action)
        {
            for (int i = 0; i < enumerable.Count(); i++)
            {
                action(i);
            }
            return enumerable;
        }

5. 判断2个集合是否相等(值也相等)

 

public static bool EqualValue<T>(this IEnumerable<T> enumerable1, IEnumerable<T> enumerable2)
        {
            if (enumerable1 == enumerable2)
                return true;
            if (enumerable1.Count() != enumerable2.Count())
                return false;
            for (int i = 0; i < enumerable1.Count(); i++)
            {
                if (!enumerable1.ElementAt(i).Equals(enumerable2.ElementAt(i)))
                    return false;
            }
            return true;
        }

6. 给集合增加一个数据项。

 

public static IEnumerable<T> Add<T>(this IEnumerable<T> enumerable, T item)
        {
            foreach (var obj in enumerable)
            {
                yield return obj;
            }
            yield return item;
        }

7. 给集合减去一个数据项。

 

public static IEnumerable<T> Remove<T>(this IEnumerable<T> enumerable, T item)
        {
            foreach (var obj in enumerable)
            {
                if (!obj.Equals(item))
                    yield return obj;
            }
        }

8. 倒着去数组N个数据项。

 

public static IEnumerable<T> GetFromEnd<T>(this T[] array, int count)
        {
            for (int i = array.Length - 1; i > array.Length - 1 - count; i--)
            {
                yield return array[i];
            }
        }

 

 

 

 

posted @ 2010-01-23 21:17  primeli  阅读(281)  评论(0编辑  收藏  举报