如何迭代这个字典对象——myDictionary>以便Key值和元素值在同一输
本文关键字:以便 元素 myClass Key 迭代 何迭代 int myDictionary 对象 字典 List | 更新日期: 2023-09-27 18:13:17
在下面的代码中,我有一个名为InputData
的对象类,然后在字典对象中添加List<InputData[]>
作为参数,然后填充这个字典对象(包括InputData[]
),每个字典元素包含一个InputData[]
数组的列表。为了让我遍历这个字典的元素,我使用了几个子foreach
循环来获得InputData[]
的元素。
我的问题是我如何迭代这个字典对象的元素和List<InputData[]>
的元素,以便我可以在主foreach
循环中在相同的Console.WriteLine(...)
上显示每个字典元素的所有数据?
现在我有一个主foreach
循环(用于这个字典对象的输出),然后是2个子foreach
循环,其中第一个子foreach
循环迭代List<...>
,第二个子foreach循环迭代InputData[]
。是否有可能访问元素数据在相同的(主)foreach
循环作为键值?
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
}
扩展我的评论,你可以这样做:
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);
以下是如何使用StringBuilder
首先构建该行,然后在控制台
StringBuilder sb = new StringBuilder();
foreach(var pr in d)
{
List<InputData[]> a = pr.Value;
//Add the key to the string builder
sb.Clear() ;
sb.Append(String.format("Key:{0}", pr.Key)) ;
foreach(var b in a)
{
foreach (var c in b)
{
if (c != null)
{
sb.Append(String.format("Data:{0}",c.dataThing));
}
}
}
Console.WriteLine(sb);
}