Join Arrays


In SQL we use join day by day. But what if we need to intersect and sort 2D arrays directly in c#? Here is my example how to join person and donut by donut type. Including * for person who likes all types 🙂 :

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Arrays
{
    public static void Join()
    {
        string[][] donutConstraintPairs =  {
            new string[] {cruller, vegan},
            new string[] {eclair, chocolate},
            new string[] { zefir, chocolate }
        };
        string[][] candidateConstraintPairs =  {
            new string[] {jose, vegan},
            new string[] {john, chocolate},
            new string[] { ian, * } //all items for the type
        };
        var join = (from d in donutConstraintPairs
                                   .Select((data, row) => new { data, row })
                                   .Select(q => new { Name = q.data[0], Type = q.data[1], Row = q.row })
                     from c in candidateConstraintPairs
                                   .Select((data, row) => new { data, row })
                                   .Select(q => new { Name = q.data[0], Type = q.data[1], Row = q.row })
                where d.Type == c.Type || c.Type == *
                select new { Person = c.Name, Donut = d.Name }
           ).OrderBy(e => e.Person)
            .ThenBy(e => e.Donut)
            .Select(e=> new[] { e.Person, e.Donut })
            .ToArray();
        for (int i = 0; i < join.Length; i++)
        {
            Console.WriteLine(string.Format({0},{1},join[i][0],join[i][1]));
        }
    }
}
Here is results of method call Arrays.Join();        :
  • ian,cruller
  • ian,eclair
  • ian,zefir
  • john,eclair
  • john,zefir
  • jose,cruller
Advertisements

About Andrew Butenko

https://www.mcpvirtualbusinesscard.com/VBCServer/a9939be0-be6f-4249-a775-6665eccff2e4/card https://www.microsoftvirtualacademy.com/Profile.aspx?alias=530492
This entry was posted in C#, SQL. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s