Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to denormalize a collection which contains a collection using Linq

Tags:

c#

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've researched it, and think that the answer lies somewhere with the SelectMany() method but I can seem to pin down the answer.

The problem is similar to: How do I select a collection within a collection using LINQ? which denormalises the collection but it doesn't show how to include the related columns (columns 1 and 2 in my example).

The difference is that I need to include the first two columns and also return a row where there are no entries in the collection.

like image 307
dubs Avatar asked Sep 29 '22 08:09

dubs


2 Answers

Using a 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);
like image 107
Dennis_E Avatar answered Nov 09 '22 23:11

Dennis_E


Suppose there are some suitable types Src and Dst for the elements of Source and Destination. Then, similar to the example from the documentation, the task can be solved with the following statement.

Dest = Source.SelectMany(
    iSrc => iSrc.Third,
    (iSrc,No) => new Dest(){ First = iSrc.First,
                             Second = iSrc.Second,
                             Third = No
                           }
);
like image 38
Codor Avatar answered Nov 09 '22 23:11

Codor