【问题标题】:Get data from a file and convert it to dictionary in unity using c#从文件中获取数据并使用 c# 将其统一转换为字典
【发布时间】:2017-11-16 10:49:26
【问题描述】:

我正在尝试从文件中读取并使用 c# 将其统一转换为字典。该文件包含类似的数据

1 1 1 acsbd 
1 2 1 123ws 

这里我想将前 6 个字符作为键和其余字符作为值。

这是我尝试过的代码(主要来自stackoverflow)

System.IO.StreamReader file = new System.IO.StreamReader (
  @"D:\Programming\Projects\Launch pad\itnol\KeySound");


     while ((line = file.ReadLine()) != null)
     {
         char[] line1 = line.ToCharArray();
         if (line1.Length >= 11)
         {
             line1[5] = ':';
             line = line1.ToString();
             //Console.WriteLine(line);
         }
         var items = line.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
             .Select(s => s.Split(new[] { ':' }));

         Dictionary<string, string> dict = new Dictionary<string, string>();
         foreach (var item in items)
         {
             Debug.Log(item[0]);
             dict.Add(item[0], item[1]);
         }

它符合但在运行时抛出IndexOutOfRangeException 异常

谢谢。

【问题讨论】:

  • 好的。然后去做。有什么问题?
  • 我想知道怎么做
  • 你尝试了什么?你被困在哪里了?你读过How to Ask吗?
  • 我编辑了问题,感谢您的帮助

标签: c# dictionary unity3d


【解决方案1】:

尝试使用 Linq

using System.IO;
using System.Linq;

...

string fileName = @"D:\Programming\Projects\Launch pad\itnol\KeySound";

...

Dictionary<string, string> dict = File 
  .ReadLines(fileName)    
  .Where(line => line.Length >= 11)           // If you want to filter out lines 
  .ToDictionary(line => line.Substring(0, 6), // Key:   first 6 characters
                line => line.Substring(6));   // Value: rest characters

编辑:没有 Linq,没有 File 版本:

string fileName = @"D:\Programming\Projects\Launch pad\itnol\KeySound";

...

Dictionary<string, string> dict = new Dictionary<string, string>();

// Do not forget to wrap IDisposable into using
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName)) {
  while (true) {
    string line = reader.ReadLine();

    if (null == line)
      break;
    else if (line.Length >= 11) 
      dict.Add(line.Substring(0, 6), line.Substring(6));
  }
}

【讨论】:

  • 如果这行得通,现在不要这样做,但它看起来又好又简单
  • 感谢您的帮助,但视觉工作室说 System.IO.File does not contain definition for ReadLines
  • @risabh kunda: ReadLines(请注意最后一个s
  • @DmitryBychenko 抱歉,这是我的评论中的拼写错误,在代码中是 ReadLines,它仍然给出同样的错误
  • @rishabh kunda:好的,让我们实现没有 Linq,没有 File 版本(参见我的编辑)。 ToCharArraySplit 中不需要,但是 Substring
猜你喜欢
  • 1970-01-01
  • 2014-11-23
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
相关资源
最近更新 更多