How to denormalize a collection containing a collection using Linq

I am trying to convert the following collection:

Source

"a", "b", {1,2,3}
"d", "f", {1,2,2}
"y", "z", {}

Destination

"a", "b", 1
"a", "b", 2
"a", "b", 3
"d", "f", 1
"d", "f", 2
"d", "f", 2
"y", "z", null

I researched it and believe that the answer lies somewhere with the SelectMany () method , but I may seem.

The problem is similar to: How to select a collection in a collection using LINQ? , which denormalizes the collection but does not show how to include related columns (columns 1 and 2 in my example).

The difference is that I need to include the first two columns, as well as return a row in which there are no entries in the collection.

+4
source share
3 answers

Using the list of tuples as an example:

var source = new List<Tuple<string, string, int[]>> {
    Tuple.Create("a", "b", new int[] {1,2,3}),
    Tuple.Create("d", "f", new int[] {1,2,2}),
    Tuple.Create("y", "z", new int[0])
};


var destination =
from t in source
from i in t.Item3.Select(x => (int?)x).DefaultIfEmpty()
select Tuple.Create(t.Item1, t.Item2, i);
+1
source

, Source Destination Src Dst. , , .

Dest = Source.SelectMany(
    iSrc => iSrc.Third,
    (iSrc,No) => new Dest(){ First = iSrc.First,
                             Second = iSrc.Second,
                             Third = No
                           }
);
+2

Check one of the possible solutions:

var source = new List<Tuple<string, string, int[]>>{
        new Tuple<string,string,int[]>("a", "b", new int[]{1,2,3}),
        new Tuple<string,string,int[]>("d", "f", new int[]{1,2,2}),
        new Tuple<string,string,int[]>("y", "z", new int[]{})
    };

    var destination = source.SelectMany(
        tuple => tuple.Item3.Length == 0 ? new int?[] { null } : tuple.Item3.Cast<int?>(),
            (tuple, collectionElement) => new { tuple.Item1, tuple.Item2, collectionElement }
    ).ToList();
0
source

All Articles