Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

foreach with a string and Hashtable

Status
Not open for further replies.

Dayton2

Programmer
Feb 4, 2004
6
0
0
US
Is it possible to search through a Hashtable by a string using foreach? I am new to C# and seem to be struggling with correctly implementing the foreach statement. I am attempting to grab each word from a readline and put them individually in a hashtable. This is code that I am working with...

Code:
Hashtable table = new Hashtable();
StreamReader sr = File.OpenText(FILE_NAME);
String linetext = sr.ReadLine();
int i = 0;

foreach (string s in linetext)
{
     table.Add(i, s);
     i++;
}
[\code]
The error that I am getting is "cannot convert 'char' to 'string'", but I am never declaring a char???
Any suggestions???
Thanks!!
 
I'm pretty sure the error is with this line:
Code:
foreach (string s in linetext)
What is essentially happening is you are moving through a collection of chars not strings (strings are just an array of characters). The following code would be correct, but not what you are looking for:
Code:
foreach (char c in linetext)

You are attempting to add each "word" in the linetext string to the hashtable? If this is correct try this:
Code:
string[] words = linetext.Split(new char[] {' '});
foreach(string s in words)
...

The Split method breaks the string into an array of words.

I hope this helped!

--
Casey Winans
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top