Sunday, 4 June 2017

LINQ 12 Concat

SQL has union and linq has concat, concat is a way to join multiple collections of elements

using System;
using System.Linq;

namespace pc.linq10
{
    class Program
    {
        static void Main(string[] args)
        {
            var nums = Enumerable.Range(0, 10);
            var chars = "Hello world".ToCharArray();
            var names = new string[] { "Pawel", "Magda", "Tomek" };

            var result1 = (from n in nums
                           select n.ToString())
                            .Concat(from c in chars
                                    select c.ToString())
                            .Concat(names);

            Array.ForEach(result1.ToArray(), n => Console.Write(n + ", "));
            Console.WriteLine();

            var result2 = nums.Select(n => n.ToString())
                .Concat(chars.Select(c => c.ToString()))
                .Concat(names);

            Array.ForEach(result2.ToArray(), s => Console.Write(s + ", "));
            Console.WriteLine();
        }
    }
}

We mentioned that not all method based linq statements have an expression based equivalent however this doesn't prevent us from using mixed syntax in our linq queries.