LINQ"拉链"在字符串数组 [英] LINQ "zip" in String Array

查看:131
本文介绍了LINQ"拉链"在字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,有两个数组:

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



我需要过滤掉上述阵列时,用户值为空再加入或拉链两者结合起来。最终输出应该是这样的:

I need to filter out the above array when the user value is Empty then join or zip the two together. Final Output should be like:

{ "One:rob", "three:john" } 

如何才能做到这一点使用LINQ?

How can this be done using LINQ?

推荐答案

这听起来像你真的想拉链的数据一起(不参加) - 即两两匹配;那是对的吗?如果是这样,简单地说:

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);



使用邮编操作=htt​​p://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx>这里:

using the Zip operation from here:

// http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>
(this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> 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<TResult> ZipIterator<TFirst, TSecond, TResult>
    (IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector)
{
    using (IEnumerator<TFirst> e1 = first.GetEnumerator())
    using (IEnumerator<TSecond> e2 = second.GetEnumerator())
        while (e1.MoveNext() && e2.MoveNext())
            yield return resultSelector(e1.Current, e2.Current);
}

这篇关于LINQ&QUOT;拉链&QUOT;在字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆