argoneus
argoneus

Reputation: 1147

What's the best way to print all properties in a list of objects?

Say you had this:

class A
{
    public string name;
}

And then you have a List<A> and want to print the name of each object.
Normally, if you wanted to just print the items, you'd do something like

String.Join(", ", myList);

But I need to print the name property, not the myList object names. Is there an easier way than a foreach?

Upvotes: 3

Views: 3301

Answers (2)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Use

String.Join(", ", myList.Select(x => x.name));

For it you have to include System.Linq namespace

EDIT:

If you want to go for Adam's answer after his code do what this

String.Join(", ", myList.Select(x => x.ToString()));

Courtesy Adam Goss comment on answer:

You wouldn't need to call .Select(x => x.ToString()) as it would be called internally by object inside String.Join(), so if you override ToString(), you just call String.Join(", ", myList);

So after his code do what you had thought

String.Join(", ", myList);

Upvotes: 13

Adam Goss
Adam Goss

Reputation: 1027

If you only want the name property, then the best way really would be to override to ToString() method on class A.

public override String ToString()
{
    return name;
}

If you have more properties, adjust your ToString() to match:

public override String ToString()
{
    return String.Format("Name: {0}. Prop1: {1}", name, prop1);
}

etc...

Upvotes: 2

Related Questions