【问题标题】:How to access a class element which is a List<string> in C#? [duplicate]如何访问 C# 中 List<string> 的类元素? [复制]
【发布时间】:2020-05-26 11:12:26
【问题描述】:

我很难获得某个类别的物品的价值。 我正在编写一种读取 CSV 文件的方法。我将我需要的数据绑定到一个类中。我的班级如下所示:

public class DatafromCSV
{
    public string ImageId { get; set; }
    public List<string> ImageBbox { get; set; }
    public string Classname { get; set; }

}

这是我读取 CSV 文件的方法。

public static DatafromCSV ReadfromCSV (string path)
    {
        List<string> csvLines = new List<string>();            

        csvLines = File.ReadAllLines(path).ToList();
        csvLines = csvLines.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();

        DatafromCSV currentRecord = new DatafromCSV();
        foreach (string line in csvLines)
        {
            string[] items = line.Split(',', '.');               

            currentRecord.ImageId = items[0];
            currentRecord.ImageBbox = new List<string>() { items[2], items[3], items[4], items[5] };
            currentRecord.Classname = items[6];

        }

        return currentRecord;
    }

我按如下方式初始化我的方法:

var infoCSV = ReadfromCSV(path);

初始化函数后,我可以访问 ImageId 和 Classname 值:

Console.WriteLine(infoCSV.ImageId);

但是,当我尝试访问 ImageBbox 时,我得到以下信息:

Console.WriteLine(infoCSV.ImageBbox);

System.Collections.Generic.List`1[System.String]

我希望得到:

[2012,1367,2284,1473]

我如何称呼它或我的方法有问题吗?我已经尽我所能,但没有任何成功。我怎样才能得到我需要的东西?

【问题讨论】:

    标签: c# csv


    【解决方案1】:

    您可以使用string.Join() 将列表打印到控制台。

    Console.WriteLine($"[{string.Join(", ", infoCSV.ImageBbox)}]");
    

    From MSDN: string.Join()

    连接指定数组的元素或数组的成员 集合,在每个元素之间使用指定的分隔符或 会员。

    【讨论】:

      【解决方案2】:

      List&lt;T&gt; 没有实现自定义的ToString 方法覆盖。所以你得到了默认的,它给你类型。

      如果你想打印出列表中的元素,就像使用string.Join一样简单:

      Console.WriteLine($"[{string.Join(",", infoCSV.ImageBbox)}]");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-18
        • 2018-12-29
        • 1970-01-01
        • 2020-07-29
        相关资源
        最近更新 更多