0

我正在尝试将 .txt 文件中的值导入我的dictionary. .txt 文件的格式如下:

唐老鸭, 2010-04-03

依此类推……每行都有 1 个这样的条目。当我尝试将拆分字符串添加到dictionary.

我正在尝试这样: scoreList.Add(values[0], values[1]); 但它说名称在上下文中不存在。我希望有人能指出我正确的方向......

谢谢!

    private void Form1_Load(object sender, EventArgs e)
    {
          Dictionary<string, DateTime> scoreList = new Dictionary<string, DateTime>();
          string path = @"list.txt";
          var query = (from line in File.ReadAllLines(path)
                       let values = line.Split(',')
                       select new { Key = values[0], Value = values[1] });

          foreach (KeyValuePair<string, DateTime> pair in scoreList)
          {
              scoreList.Add(values[0], values[1]);
          }
          textBox1.Text = scoreList.Keys.ToString();
    }
4

3 回答 3

3

您的values变量仅在 LINQ 查询范围内。您需要枚举查询结果,并将值添加到字典中:

foreach (var pair in query)
{
    scoreList.Add(pair.Key, pair.Value);
}

话虽如此,LINQ 提供了一种ToDictionary扩展方法,可以在这里为您提供帮助。您可以将循环替换为:

scoreList = query.ToDictionary(x => x.Key, x => x.Value);

最后,为了使类型正确,您需要将 Value 转换为DateTimeusing,例如DateTime.Parse.

于 2013-02-12T19:47:06.123 回答
2

首先你做错了,你应该从列表中添加项目而不是 LINQ 中使用的 values[0] 和 values[1] ..

Dictionary<string, DateTime> scoreList = new Dictionary<string, DateTime>();

    string path = @"list.txt";

    var query = (from line in File.ReadAllLines(path)
                 let values = line.Split(',')
                 select new { Key = values[0], Value = values[1] });

    foreach (var item in query) /*changed thing*/
    {

        scoreList.Add(item.Key, DateTime.Parse(item.Value)); /*changed thing*/
    }

    textBox1.Text = scoreList.Keys.ToString();
于 2013-02-12T19:47:53.113 回答
1

代码的直接问题是它只存在于查询表达式中......您的序列有一个元素类型,它是一个具有和属性values的匿名类型。KeyValue

下一个问题是您正在迭代scoreList,一开始它是空的......而且也没有迹象表明您打算从哪里转换stringDateTime. 哦,我不确定是否Dictionary<,>.Keys.ToString()会给你任何有用的东西。

不过,您可以简单地构建字典:

var scoreList = File.ReadLines(path)
                    .Select(line => line.Split(','))
                    .ToDictionary(bits => bits[0], // name
                                  bits => DateTime.ParseExact(bits[1], // date
                                              "yyyy-MM-dd",
                                              CultureInfo.InvariantCulture));

注意使用DateTime.ParseExact而不是仅仅DateTime.Parse- 如果您知道数据的格式,则应该使用该信息。

于 2013-02-12T19:48:20.093 回答