Re: foreach with a string and Hashtable
From: Chris Taylor (chris_taylor_za_at_hotmail.com)
Date: 03/01/04
- Next message: Stoitcho Goutsev \(100\) [C# MVP]: "Re: calling unmanaged dll function with user-defined parms"
- Previous message: Miha Markic [MVP C#]: "Re: foreach with a string and Hashtable"
- In reply to: Dayton2: "foreach with a string and Hashtable"
- Messages sorted by: [ date ] [ thread ]
Date: Mon, 1 Mar 2004 22:12:15 +0200
Hi,
The foreach uses the IEnumerable interface to enumerate through the
collection, in the case of a string the IEnumrable interface implementation
enumerates the characters (char) in the string. Your foreach declaration is
attempting to read each character from linetext into the string s, hence
the error "cannot convert 'char' to 'string'".
If I understand what you are trying to achieve here is to extract each word
from the linetext variable rather than each character. In this case you have
basically three options that I can think of off the top of my head. One is
to use the Split() function to split the string on spaces and punctuation
etc, the second would be to use a regular expression (see Regex class) to
split the string into words and finally you could build a parser to parse
the string and split it according to rules that you define.
I would probably consider the Regex route.
Hope this helps
-- Chris Taylor http://dotnetjunkies.com/WebLog/chris.taylor/ "Dayton2" <mbasil@monsanto.com> wrote in message news:982DD8DF-CF31-418E-A396-C3F9601E1E38@microsoft.com... > 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!!
- Next message: Stoitcho Goutsev \(100\) [C# MVP]: "Re: calling unmanaged dll function with user-defined parms"
- Previous message: Miha Markic [MVP C#]: "Re: foreach with a string and Hashtable"
- In reply to: Dayton2: "foreach with a string and Hashtable"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|