有时我们需要合并两个集合,并同时做一些修改。下面我们实现一个扩展方法在IEnumerable<T>上,看下面的代码:

   public static class IEnumerableExtensions
    {
        /// <summary>
        /// Combines the specified seq A and B
        /// </summary>
        /// <typeparam name="TA"></typeparam>
        /// <typeparam name="TB"></typeparam>
        /// <typeparam name="T"></typeparam>
        /// <param name="seqA">The seq A.</param>
        /// <param name="seqB">The seq B.</param>
        /// <param name="func">The func.</param>
        /// <returns>IEnumerable list</returns>
        public static IEnumerable<T> Combine<TA, TB, T>(
            this IEnumerable<TA> seqA, IEnumerable<TB> seqB, Func<TA, TB, T> func)
        {
            using (var iteratorA = seqA.GetEnumerator())
            using (var iteratorB = seqB.GetEnumerator())
            {
                bool hasValueA;
                bool hasValueB;
                do
                {
                    hasValueA = iteratorA.MoveNext();
                    hasValueB = iteratorB.MoveNext();
 
                    if (hasValueA | hasValueB)
                    {
                        TA a = hasValueA ? iteratorA.Current : default(TA);
                        TB b = hasValueB ? iteratorB.Current : default(TB);
                        yield return func(a, b);
                    }
                } while (hasValueA || hasValueB);
            }
        }
    }

如何使用,看UnitTest:

   1:          [Test]
   2:          public  void TestIEumberableExtention()
   3:          {
   4:              int[] integers1 = new int[] { 1, 2, 3, 4, 5 };
   5:              int[] integers2 = new int[] { 10, 20, 30, 40, 50 };
   6:   
   7:              //Sums
   8:              CollectionAssert.AreEqual(new int[] { 11, 22, 33, 44, 55 }, integers1.Combine(integers2, (i, j) => i + j));
   9:   
  10:              char[] characters = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
  11:   
  12:              //Mixed Types and Lengths
  13:              CollectionAssert.AreEqual(new [] { "A1","B2","C3","D4","E5","F0" },characters.Combine(integers1, (c, i) => string.Format("{0}{1}", c, i)));
  14:          }

希望这篇POST对您有帮助。


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

posted on 2010-11-17 10:48  PetterLiu  阅读(1081)  评论(1编辑  收藏  举报