0

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.

5 Answers 5

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ah, yeah it is just one of those days. I figured it would be something mind-numbingly apparent like that...thank you!
No problem. We've all been there.
better yet, use var instead of string : foreach(var result in stringList)
3

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)

Comments

3

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
}

Comments

3

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)

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.