wjhguitarman
wjhguitarman

Reputation: 1073

Foreach Variable Error

I am clearly just missing something with this. I have the following:

   List<string> stringList = new List<string>();

I then fill it with some data and do the following:

   foreach (List<string> results in stringList)

But it errors claiming that it "cannot convert from type string to type System.Generic.Collections.List<string>" ...but both are of type List<string> so where is the disconnect? I am sure there must be something very simple I'm clearly doing wrong, but for the life of me I cannot find it.

Upvotes: 0

Views: 198

Answers (5)

erictrigo
erictrigo

Reputation: 1017

stringList is of type List<string>.

That means that every element of your list stringList is going to be a string. So when you do a foreach (element in stringList), element is expected to be a string.

The most recommended way to solve your issue is to substitute the List<string> inside your foreach for var. If you always use var in a foreach statement, it will automatically consider the correct type (which in this case would be string instead of List<string>), so you don't have to worry about finding out what type your element is.

Upvotes: 3

Bort
Bort

Reputation: 7638

When you foreach over a list, you are enumerating the elements in the list. stringList contains strings, so you need do to:

foreach (string s in stringList)

Upvotes: 3

Platinum Azure
Platinum Azure

Reputation: 46233

When you use a foreach loop in C#, you are iterating through a collection type and performing an operation repeatedly using a single value from that collection. Therefore, for a generic collection type, you want the individual item type in your foreach loop.

List<string> stringList = new List<string>();
foreach (string stringItem in stringList)
{
    // do something
}

Upvotes: 3

McGarnagle
McGarnagle

Reputation: 102793

A for-each iteration gives you the items one at a time, so the type should be string, not List<string>:

foreach (string result in stringList)

Upvotes: 3

PiousVenom
PiousVenom

Reputation: 6918

Your foreach should be:

foreach(string s in stringList).

In your code, you're checking for a list of strings in the stringList, instead of the strings in the list.

Upvotes: 11

Related Questions