LINQ - UNION
Select/Combine elements from different arrays

Say I have 2 string arrays.

string[] animals = new string[5] { "Ape", "Ant", "Dog", "Cat", "Elephant" };
string[] birds = new string[5] { "Auk", "Brant", "Catbird", "Cuckoo", "Cygnet" };


Now I want to select the animals and birds starts with letter 'A'
Here you go for the sample.

namespace My_Samples
{
using System;
using System.Linq;

class Program
{
static void Main(string[] args)
{
string[] animals = new string[5] { "Ape", "Ant", "Dog", "Cat", "Elephant" };
string[] birds = new string[5] { "Auk", "Brant", "Catbird", "Cuckoo", "Cygnet" };

var result = (from a in animals
where a[0].Equals('A')
select a)
.Union(from b in birds
where b[0].Equals('A')
select b);

foreach (string s in result)
{
Console.WriteLine(s);
}

Console.ReadLine();
}
}
}

No comments:

Post a Comment