Foreach and custom objects | SoloLearn: Learn to code for FREE!


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); } Both the second and third foreach are not working for obvious reason. It there a way to do it like that ?

8/4/2019 7:59:18 PM


1 Answer

New Answer


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! 😉