c# - 如何在 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}");
}
解决方案
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)
推荐阅读
- d3.js - 使用 D3js 在线图上显示标签时出错
- c# - DllNotFoundException:gda-2
- android - Flutter - 从 SharedPreferences 传递的数据显示为 null
- c# - datagridview 中缺少外键列
- math - 来自两个角度和距离的 3D 点
- python-3.x - Python 3:igraph 不生成任何图像
- java - 将额外的辅助工件上传到现有工件
- ios - iOS中带点的数字键盘?
- notifications - 在客户端管理 apns 通知令牌
- c# - WPF DisplayMemberProperty 在后面的代码中未按预期运行