LINQ “zip” in String Array

前端 未结 5 785
春和景丽
春和景丽 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:31

    It sounds like you actually want to "zip" the data together (not join) - i.e. match pairwise; is that correct? If so, simply:

        var qry = from row in title.Zip(user, (t, u) => new { Title = t, User = u })
                  where !string.IsNullOrEmpty(row.User)
                  select row.Title + ":" + row.User;
        foreach (string s in qry) Console.WriteLine(s);
    

    using the Zip operation from here:

    // http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx
    public static IEnumerable Zip
    (this IEnumerable first,
    IEnumerable second,
    Func resultSelector)
    {
        if (first == null) throw new ArgumentNullException("first");
        if (second == null) throw new ArgumentNullException("second");
        if (resultSelector == null) throw new ArgumentNullException("resultSelector");
        return ZipIterator(first, second, resultSelector);
    }
    
    private static IEnumerable ZipIterator
        (IEnumerable first,
        IEnumerable second,
        Func resultSelector)
    {
        using (IEnumerator e1 = first.GetEnumerator())
        using (IEnumerator e2 = second.GetEnumerator())
            while (e1.MoveNext() && e2.MoveNext())
                yield return resultSelector(e1.Current, e2.Current);
    }
    

提交回复
热议问题