Combine one or more generic lists in C#


One or more generic lists can be combined or merged using zip() method in C#.

Below is an example of combining 4 lists by creating an extension method.

public static IEnumerable<TResult&gt; ZipFour<T1, T2, T3, T4, TResult&gt;(
            this IEnumerable<T1&gt; source,
            IEnumerable<T2&gt; second,
            IEnumerable<T3&gt; third,
            IEnumerable<T4&gt; fourth,
            Func<T1, T2, T3, T4, TResult&gt; func)
        {
            using (var e1 = source.GetEnumerator())
            using (var e2 = second.GetEnumerator())
            using (var e3 = third.GetEnumerator())
            using (var e4 = fourth.GetEnumerator())
            {
                while (e1.MoveNext() &amp;&amp; e2.MoveNext() &amp;&amp; e3.MoveNext() &amp;&amp; e4.MoveNext())
                    yield return func(e1.Current, e2.Current, e3.Current, e4.Current);
            }
        }

Usage

list1.ZipFour(list2, list3, list4, (a, b, c, d) => new { A = a, B = b, C = c, D = d });

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.