rich dvc rich dvc - 1 month ago 16
C# Question

how to iterate this dictionary object -- myDictionary<int, List<myClass[]>> so that the Key and element values are on the same output line?

In the following code I have an object class called

InputData
, and then in a dictionary object I add a
List<InputData[]>
as a parameter, and then I populate this dictionary object (including
InputData[]
), and each dictionary element contains a List of an
InputData[]
array. In order for me to iterate through the elements of this dictionary I use a couple of sub
foreach
loops to get to the elements of
InputData[]
.

My question is How can I iterate the elements of this dictionary object and the elements of
List<InputData[]>
so that I can display all the data for each dictionary element on the same
Console.WriteLine(...)
in the main
foreach
loop?

Right now I have a main
foreach
loop (for the output of this dictionary object) and then 2 sub
foreach
loops where the first sub
foreach
loop iterates the
List<...>
and the 2nd sub foreach loop itereates
InputData[]
. Is it possible to access the element data in the same (main)
foreach
loop as the Key value?

class InputData
{
public int dataId;
public int dataQtr;
public string dataThing;

public InputData(int DataId, int DataQtr, string DataThing)
{
dataId = DataId;
dataQtr = DataQtr;
dataThing = DataThing;
}
}

//----------------------------------------------------

List<InputData> input_rows = new List<InputData>
{
new InputData(1, 1, "chair" ),
new InputData(1, 1, "mug" ),
new InputData(1, 2, "bottle" ),
new InputData(1, 3, "dog" ),
new InputData(2, 2, "snake" ),
new InputData(2, 3, "horse" ),
new InputData(3, 2, "cup" ),
new InputData(3, 3, "boomerang" ),
new InputData(3, 3, "girl" ),
new InputData(3, 4, "walkman" ),
};

Dictionary<int, List<InputData[]>> d = new Dictionary<int, List<InputData[]>>();

foreach( var row in input_rows )
{
List<InputData[]> list;
if( !d.TryGetValue( row.dataId, out list ) )
{
var a = new InputData[4];
a[row.dataQtr - 1] = row;
d.Add( row.dataId, new List<InputData[]> { a } );
}
else
{
var fa = list.FirstOrDefault( a => a[row.dataQtr - 1] == null );
if( fa == null )
{
var a = new InputData[4];
a[row.dataQtr - 1] = row;
list.Add( a );
}
else
{
fa[row.dataQtr - 1] = row;
}
}
}

//--is there a way I could eliminate to the 2 sub foreach loops here? How?
foreach(var pr in d)
{
List<InputData[]> a = pr.Value;
foreach(var b in a)
{
foreach (var c in b)
{
if (c != null)
Console.WriteLine(c.dataThing);
}
}
Console.WriteLine(pr.Key); //--I want to display c.dataThing on the same line as pr.Key
}

Answer

Expanding on my comment, you can do this:

var output = d.Select(i => new { Key = i.Key, Value = string.Join(" ", i.Value.SelectMany(v => v.SelectMany(t => t.dataThing ?? ""))));
foreach(var o in output) Console.WriteLine(output.Key + " " + output.Value);
Comments