0

Foreach and custom objects

Is it possible to print a property of a custom object in a foreach loop ? The custom object is Person and has a property called Name. I want to print all names of the persons in the personslist (PList) This is the standard way of doing it. It is good, no doubt about that. foreach (Person X in PList) //good one { Console.WriteLine(X.Name); } Some where I have seen that people used something like this. If you know you are only interrested in the string Name, you could do it. foreach (Person.Name Y in PList) { Console.WriteLine(Y); } foreach (var Z.Name in PList) { Console.WriteLine(Z); } https://code.sololearn.com/cmysAzng96Fx Both the second and third foreach are not working for obvious reason. It there a way to do it like that ?

4th Aug 2019, 7:59 PM
sneeze
sneeze - avatar
1 Antwort
+ 2
From what I know there's no straightforward way like what you've shown, the nearest I can think of would be extracting the Name property via LINQ and iterate over the IEnumerable as follows:- foreach (var name in PList.Select(p => p.Name)) { // process name here } Hopefully it helps! 😉
7th Aug 2019, 1:19 PM
Zephyr Koo
Zephyr Koo - avatar