zoukankan      html  css  js  c++  java
  • 为IEnumerable<T>增加Combine的扩展方法

            有时我们需要合并两个集合,并同时做一些修改。下面我们实现一个扩展方法在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

  • 相关阅读:
    java容器
    利用java mail发送邮件
    利用java mail发送邮件
    hbase java API跟新数据,创建表
    hbase java API跟新数据,创建表
    利用httpclient和mysql模拟搜索引擎
    利用httpclient和mysql模拟搜索引擎
    HBase 官方文档
    HBase 官方文档
    安装yum
  • 原文地址:https://www.cnblogs.com/wintersun/p/1879634.html
Copyright © 2011-2022 走看看