I have simple class
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; }
}
And a json file
[
{
"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"
]
}
]
I need to get in console all names or surnames, existing in Person list. I tried to use something like this:
var JsonDeserialize = File.ReadAllText(fileName);
List<Person> result = JsonSerializer.Deserialize<List<Person>>(JsonDeserialize);
Console.WriteLine(result.Select(x => x.Name).ToList());
But i don't have any idea to use it in my code. Thanks in advance.
CodePudding user response:
list of names
var names= result.Select(i=> new {Name=i.Name, Surname=i.Surname}).ToList();
to print
foreach (var n in result) Console.WriteLine ( $"{n.Name} {n.Surname}");
CodePudding user response:
If you want to customise how you display information in a class one option is to override ToString()
for your Person
class:
class Person
{
...
// customize however you like
public override string ToString() => $"{Name} {Surname}";
}
Then to display in a single line, you could use string.Join()
:
Console.WriteLine(string.Join(", ", result));
Or if you want each person on a new line:
result.ForEach(person => Console.WriteLine(person));
// which can be shortened to
result.ForEach(Console.WriteLine);