[英]How to convert data from two different locations in JSON file to a key(string) and value(double) within a C# dictionary, using Linq?
[英]Get data from a file and convert it to dictionary in unity using c#
我正在嘗試從文件中讀取文件,然后使用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
異常
謝謝。
嘗試使用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));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.