Erik Berkun-Drevnig
Erik Berkun-Drevnig

Reputation: 2356

Is there another way to get a property of a foreach loop item?

I have noticed that a lot of times I need to do something like this

foreach (SomeObject item in listOfItems)
{
    string itemName = item.Name;

    ...
}

But I would much prefer if there was a way to do something like this:

foreach (string item.Name in listOfItems)
{
    ...
}

Is this possible in C#?

Upvotes: 1

Views: 100

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460058

You can use LINQ:

foreach (string name in listOfItems.Select(item => item.Name))
{
    // ...
}

Upvotes: 15

Related Questions