简体   繁体   English

C# 字典按位置打印列表值

[英]C# Dictionary print list values by position

From this example: https://stackoverflow.com/a/27034916/1312879从这个例子: https : //stackoverflow.com/a/27034916/1312879

I have this kind of dictionary我有这种字典

Dictionary<int, List<string>> fileList = new Dictionary<int, List<string>>();

The example prints "fijo", "Frigy", "lijo", "liji", "vimal", "vilma"该示例打印“fijo”、“Frigy”、“lijo”、“liji”、“vimal”、“vilma”

How can I print "fijo", "lijo", "vimal", "Frigy", "liji", "vilma", I mean all the [0] position of each list, the [1] position and so on如何打印“fijo”、“lijo”、“vimal”、“Frigy”、“liji”、“vilma”,我的意思是每个列表的所有 [0] 位置、[1] 位置等等

You can code pretty much as you said:你可以像你说的那样编码:

foreach (var kvp in fileList)
{
    Console.WriteLine (kvp.Value[0]);
}
foreach (var kvp in fileList)
{
    Console.WriteLine (kvp.Value[1]);
}

And if there is more item in the inner list, you might want to use a loop for that, assuming they all have the same length:如果内部列表中有更多项目,您可能需要为此使用循环,假设它们都具有相同的长度:

for (int i = 0; i < fileList.First().Value.Count; i++)
{
    foreach (var kvp in fileList)
    {
        Console.WriteLine (kvp.Value[i]);
    }
}

Here you go:干得好:

for(int i=0; i < fileList.Values.Max(v=> v==null ? 0 : v.Length); i++)
{
    foreach(var keyValuePair in fileList)
    {
        if(kvp.Value == null || i >= kvp.Value.Length)
            continue;
        Console.WriteLine(kvp.Value[i]);
    }
}

However, I wonder reason behind traversing data structure in columnar fashion when it was created based on rows (or vice versa).但是,我想知道在基于行创建数据结构时以列方式遍历数据结构背后的原因(反之亦然)。 You may be better off using different data structure that can serve all use cases.您最好使用可以服务于所有用例的不同数据结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM