将列表<键值对<字符串,列表<字符串>>>写入文本文件

本文关键字:字符串 列表 文本 文件 键值对 | 更新日期: 2023-09-27 18:33:09

我想知道是否有人知道写这个的好方法。我有一个键值对列表。键是一个简单的字符串,值是字符串列表。我正在尝试将其写出到输出文件中,如下所示:

        File.WriteAllLines(@"C:'Users'S'Downloads'output.txt",
            xEleAtt.Select(x => x.Key + " Val's: " + x.Value).ToArray());

但是我得到的输出(这有点像我认为会发生的)是这样的:

Queue0 Val's: System.Collections.Generic.List'1[System.String]

Queue1 Val's: System.Collections.Generic.List'1[System.String]

Queue2 Val's: System.Collections.Generic.List'1[System.String]

有没有人知道我如何使用以我编写的方式编写的 linq 打印列表的内容?

将列表<键值对<字符串,列表<字符串>>>写入文本文件

您可以使用

String.JoinList<string>连接到具有给定分隔符的单个string中:

File.WriteAllLines(@"C:'Users'S'Downloads'output.txt",
        xEleAtt.Select(x => x.Key + " Val's: " + 
        string.Join(",", x.Value.ToArray()).ToArray());

试试这个:

File.WriteAllLines(@"C:'Users'S'Downloads'output.txt",
    from kvp in input
    select kvp.Key + ": " + string.Join(", ", kvp.Value));
File.WriteAllLines(@"C:'Users'S'Downloads'output.txt",
         xEleAlt.SelectMany(x=> x.Value, (x,y)=> x.Key + " Val's: " + y).ToArray());
//Result
Queue0  ....
Queue0  ....
......
Queue1  ....
Queue1  ....
....

注意:我不确定您是否要连接List<string>中的所有字符串以为每个条目生成值。如果您愿意,请参考以下答案 Douglas