首页 > 解决方案 > 如何在 C# 中正确访问对象的 List<> 值?

问题描述

我正在尝试获取对象值,但我不知道该怎么做。我是 C# 的新手,它给了我语法错误。我想通过“PrintSample”方法单独打印它我怎样才能连接或附加whatData变量。谢谢你。

PrintSample(getData, "name");
PrintSample(getData, "phone");
PrintSample(getData, "address");


//Reading the CSV file and put it in the object
string[] lines = File.ReadAllLines("sampleData.csv");
            var list = new List<Sample>();
            foreach (var line in lines)
            {
                var values = line.Split(',');
                var sampleData = new Sample()
                {
                    name = values[0],
                    phone = values[1],
                    address = values[2]
                };
                list.Add(sampleData);

            }

 public class Sample
        {
            public string name { get; set; }
            public string phone { get; set; }
            public string adress { get; set; }
        }
//Method to call to print the Data
 private static void PrintSample(Sample getData, string whatData)
        {
            //THis is where I'm having error, how can I just append the whatData to the x.?
            Console.WriteLine( $"{getData. + whatData}"); 
            
        }

标签: c#

解决方案


PO真正需要的是

private static void PrintSamples(List<Sample> samples)
{
foreach (var sample in samples)
Console.WriteLine($"name : {sample.name} phone: {sample.phone} address: {sample.address} ");
}

和代码

 var list = new List<Sample>();
 foreach (var line in lines)
   {
     ......
     }
   PrintSamples(list);

使用它是激进的

PrintSample(getData, "name");

而不仅仅是

PrintSample(getData.name)

推荐阅读