LINQ “zip” in String Array

前端 未结 5 762
春和景丽
春和景丽 2020-12-10 14:15

Say there are two arrays:

String[] title = { \"One\",\"Two\",\"three\",\"Four\"};
String[] user = { \"rob\",\"\",\"john\",\"\"};

I need to

5条回答
  •  失恋的感觉
    2020-12-10 14:27

    As another addition to the previous answers, Zip is usually defined and used in conjunction with a Tuple type. This relieves the user of having to provide a resultSelector function.

    public class Tuple // other definitions for higher arity
    {
        public TItem1 Item1 { get; private set; }
        public TItem2 Item2 { get; private set; }
    
        public Tuple(TItem1 item1, TItem2 item2)
        {
            Item1 = item1;
            Item2 = item2;
        }
    }
    

    And hence:

    public static IEnumerable> Zip
        (this IEnumerable first, IEnumerable second) 
    {
        using (IEnumerator e1 = first.GetEnumerator())
        using (IEnumerator e2 = second.GetEnumerator())
        {
            while (e1.MoveNext() && e2.MoveNext())
                yield return new Tuple(e1.Current, e2.Current);
        }
    }
    

    I believe this is closer to what CLR 4.0 will have (though it may have the more flexible variety as well).

提交回复
热议问题