Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Say there are two arrays:

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" } 

How can this be done using LINQ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
191 views
Welcome To Ask or Share your Answers For Others

1 Answer

For a start, you need a Zip operator to zip the two arrays together. Here's an abbreviated version of the code from Eric Lippert's blog (no error checking in this version, just for brevity):

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>
    (this 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);
}

Note that Zip will be in the standard libraries for .NET 4.0.

Then you need to just apply a filter and a projection. So we'd get:

var results = title.Zip(user, (Title, User) => new { Title, User })
                   .Where(x => x.Title != "")
                   .Select(x => x.Title + ":" + x.User);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...