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.
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);
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
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With