Return multiple rows from a select new using linq
Solution 1
I would do:
var DRows = from inputRow in inputTable.AsEnumerable()
where inputRow.D == 'some value'
select new outputRow(inputRow, *delegateToProcessor*)
var ERows = from inputRow in inputTable.AsEnumerable()
where inputRow.E == 'some value'
select new outputRow(inputRow, *delegateToProcessor*)
var FRows = from inputRow in inputTable.AsEnumerable()
where inputRow.F == 'some value'
select new outputRow(inputRow, *delegateToProcessor*)
return DRows.Union(ERows).Union(FRows);
Solution 2
Create a function like this:
public IEnumerable<OutputRow> GetOutputRows(InputRow input)
{
if ( ** some condition on input.D ** )
yield return new OutputRow(inputRow, *delegateToProcessor*);
if ( ** some condition on input.E ** )
yield return new OutputRow(inputRow, *delegateToProcessor*);
if ( ** some condition on input.F ** )
yield return new OutputRow(inputRow, *delegateToProcessor*);
}
and your query goes like this:
var outputRows = from inputRow in inputTable.AsEnumerable()
from row2 in GetOutputRows(inputRow)
select row2;
Comments
-
Codex almost 2 years
We need to transpose data from the rows in a table to the output table such that that multiple rows are returned for every row in the input table. The logic for extracting data in each row of the output depends if value is present in a given column in the input row.
For e.g.
Input table
A, B, C, D, E, F
Output table
A, B, C, [if value present in D then some operation on value in D]
A, B, C, [if value present in E then some operation on value in E]
A, B, C, [if value present in F then some operation on value in F]
For doing this I intend to something like this:
private IEnumerable<OutputRow> BuildOutputTable(DataTable inputTable) { var outputRows = from inputRow in inputTable.AsEnumerable() select new outputRow(inputRow, *delegateToProcessor*); return gbbOutputRows; }
But this will need me to iterate through for each of the additional value columns. Can I avoid that and just pass a single delegate so that the 'select new outputrow' returns me multiple rows?
-
NetMage over 6 yearsI think
Concat
is better thanUnion
here.