我有一个简单的类
class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public List<string> ParentsNames { get; set; }
}
和一个json文件
[
{
"Name": "Frank",
"Surname": "Wilson",
"Age": "52",
"Login": "fwillock",
"Password": "willock123",
"ParentsNames": [
"Charles",
"Sarah"
]
},
{
"Name": "Karen",
"Surname": "Davies",
"Age": "35",
"Login": "kdavies",
"Password": "davies123",
"ParentsNames": [
"Jason",
"Angela"
]
}
]
我需要在控制台中获取Person列表中现有的所有姓名。我试着用这样的东西:
var JsonDeserialize = File.ReadAllText(fileName);
List<Person> result = JsonSerializer.Deserialize<List<Person>>(JsonDeserialize);
Console.WriteLine(result.Select(x => x.Name).ToList());
但是我不知道在我的代码中使用它。提前谢谢。
名称列表
var names= result.Select(i=> new {Name=i.Name, Surname=i.Surname}).ToList();
打印
foreach (var n in result) Console.WriteLine ( $"{n.Name} {n.Surname}");
如果您想自定义在类中显示信息的方式,一个选项是覆盖Person
类的ToString()
:
class Person
{
...
// customize however you like
public override string ToString() => $"{Name} {Surname}";
}
然后,要在单行中显示,可以使用string.Join()
:
Console.WriteLine(string.Join(", ", result));
或者,如果你想让每个人都在一条新的线上:
result.ForEach(person => Console.WriteLine(person));
// which can be shortened to
result.ForEach(Console.WriteLine);