简体   繁体   English

LINQ Select返回Null

[英]LINQ Select returns Null

I am reading a csv file and placing it in this structure: 我正在读取一个csv文件,并将其放在以下结构中:

List<Dictionary<string, object>> l = new List<Dictionary<string, object>>();

The CSV File contains: CSV文件包含:

cod_curso; name
3; language
5; math
6; physic

The code I have to do this is: 我要做的代码是:

    string path = "test.csv";
    List<Dictionary<string, object>> l = new List<Dictionary<string, object>>();

    using (var reader = new StreamReader(path))
    {
        var header = reader.ReadLine();
        var keys = header.Split(";");

        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var values = line.Split(';');

            for (int i = 0; i < values.Length; i++)
            {
                Dictionary<string, object> d = new Dictionary<string, object>();
                d.Add(keys[i], values[i]);
                l.Add(d);
            }
        }
    }

To go through the structure I use the following: 要遍历该结构,请使用以下命令:

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

What I'm trying to do is select the values of the dictionary by key, but it does not work for me, by doing: 我想做的是通过键选择字典的值,但是这样做对我不起作用:

var b = l.Select(a => a["cod_curso"]);

I get null. 我得到空。

"cod_curso" is a column of the csv file and is as a key in the dictionary “ cod_curso”是csv文件的一列,并作为字典中的键

The next image is what I get in the debug 下一张图片是我在调试中得到的

除错

How could I achieve what I am looking for? 我怎样才能达到我想要的? Or why does this happen? 还是为什么会这样?

You want each dictionary to be created and added outside the inner loop, like: 您希望在内部循环外部创建和添加每个字典,例如:

    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        var values = line.Split(';');
        var d = new Dictionary<string, object>(); // New dictionary for each line

        for (int i = 0; i < values.Length; i++)
        {
            d.Add(keys[i], values[i]);
        }

        l.Add(d);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM