如何并排显示列表和列表列表

How do I display a list and a list of lists side by side

我找到了一个可以并排显示两个列表的代码,但是一个列表和一个列表的列表没有成功

这是两个并排列表的代码

for (var i = 0; i < bncount; i++)
{
  //Console.WriteLine(String.Format("{0,-10} | {1,-10}", hed.ElementAt(i),bin.ElementAt(i)));
  Console.WriteLine(String.Format("{0,-10} | {1,-10}", i< hdcount ? hed[i] : string.Empty, i< bncount ? bin[i] : string.Empty));          
}

但是 string.empty 仅适用于列表而不是列表列表,ElementAt() 也不起作用 我尝试将 linq 与 foreach 一起使用但没有成功

hed 是字符串列表,bn 是数字序列列表的列表

我的输出如下

foreach(var r in bin) //0010 1110 1111
foreach(var m in hed) //red blue white 

我想要以下输出

red 0010
blue 1110
white 1111

red   blue  white
 0     1      1     
 0     1      1     
 1     1      1
 0     0      1  

关于如何在 C# 中或在 Linq 中执行此操作的任何想法?我尝试的方法要么导致仅从 a hed 重印一个值,而从 bin 重印所有值,要么相反

我建议使用不同的结构来存储数据(考虑到 OOP 原则)并使用以下代码打印数据:

public class Item
{
    public string Name { get; set; }
    public List<int> Values { get; set; }
}

public void Print(List<Item> items)
{
    foreach (var item in items)
    {
        Console.WriteLine($"{item.Name} {string.Join("", item.Values)}");
    }
}

不确定我是否正确理解了这个问题,我认为扩展包括变量定义在内的代码示例会有所帮助。无论如何,如果我理解正确的话,这就是我的方法:

var listOfString = new List<string>( )
{
    "red",
    "blue",
    "white"
};

var listOfArrays = new List<int[]>( )
{
    new int[] { 0,0,1,0 },
    new int[] { 0,1,1,1 },
    new int[] { 1,1,1,1 }
};

// Here you could add a condition in case you are not 100% sure your arrays are of same length.
for( var i = 0; i < listOfString.Count; i++ )
{
    var stringItem = listOfString[i];
    var arrayItem = listOfArrays[i];

    Console.WriteLine( $"{stringItem} {string.Join( null, arrayItem )}" );
}

第一个版本没那么难:

string reuslt = string.Join("\n", bin.Zip(hed).Select(x => $"{x.Item1} {x.Item2}"));

使用 zip,我们创建了一个可枚举的元组,其中 n-th 元组具有 bin 的 n-th 元素和 hed 的 n-th 元素。您可以将这两项连接起来。

第二个版本有点复杂:

result = string.Join("\t",hed) + "\n" + 
       string.Join("\n",Enumerable.Range(0, bin.First().Length)
             .Select(x => string.Join("\t\t", bin.Select(str => str[x]))));

我们通过连接 hed 字符串来创建标题行。然后我们创建一个可枚举的数字,代表字符串中的索引。枚举将是 0、1、2、3。然后我们取 bin 列表中每个字符串的索引为 0 的字符,然后是 bin 列表中每个字符串的索引为 1 的字符,依此类推。

在线演示:https://dotnetfiddle.net/eBQ54N

你可以使用字典:

        var hed = new List<string>(){"red", "blue", "white"};
        var bin = new List<string>(){ "0010", "1110", "1111" };
        Dictionary<string, string> Dic = new Dictionary<string, string>();
        for (int i = 0; i < hed.Count; i++)
        {
            Dic.Add(hed[i],bin[i]);
        }

        foreach (var item in Dic)
        {
            Console.WriteLine(item.Key+" "+item.Value);
        }

        Console.ReadKey();