0

Okay, i've searched EVERYWHERE and I'm truly stuck with this. I'm trying to create a program which will load a CSV file with text words separated by a comma using a streamreader and then add them into a dictionary. Then on the form if a user types the text before the comma into the first text box and clicks a button then the text after the comma will show in the other text box.

I'm not going to lie, I'm still trying to learn to basics of c# so an explained answer would be appreciated!

This is my code just now and I don't know where to go from here, I want to use a TryGetValue after the comma split to assign the first part of the text as [0] and the second part after the comma as [1]

//Dictionary Load Button
private void button1_Click_1(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK) // Allows the user to choose the dictionary to load
    {  
        Dictionary<string, int> d = new Dictionary<string, int>();
        using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                string[] splitword = line.Split(',');
            }
        }
    }
}

an example of my input data is like:

black, white

cat,dog

yellow, blue

2 Answers2

0

I would just do something simple like below for now:

if(splitword.Length != 2)
    //Do something (log it, throw an error, ignore it, etc
    continue;
int numberVal;
if(!Int32.TryParse(splitword[1], out numberVal))
    //Do something (log it, throw an error, ignore it, etc
    continue;    
d.Add(splitword[0], numberVal);

I am not in front of a compile so this might need cleaned up, but should be pretty close.

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
  • splitword.Length gives an error that it cannot be used as a method –  Mar 16 '12 at 21:32
  • I told you that it was possibly not compilable. I have updated it now. Try to use the IDE suggestions to figure out what is needed, however this should compile now, I believe. – Justin Pihony Mar 17 '12 at 01:21
  • Thanks a lot pal! That seems to work. Just trying to figure out now how I would assign it to my text boxes. So if the first part was entered in textbox1 and the button was clicked then the second part would show in textbox2 –  Mar 17 '12 at 13:52
  • I'm thinking it would be something like, If the splitword [1] is found in textbox1 then show splitword [0] in text box 2. But i'm not sure how I'd code that –  Mar 17 '12 at 14:18
  • I can give you a hint. You will now have the values in a dictionary. So, think of a dictionary for what it is, and use it that way...you look up key values to get definitions. Maybe that can help. – Justin Pihony Mar 17 '12 at 14:46
  • I think i'm getting there! inputBx.Text = splitword[0]; outputBx.Text = splitword[1]; –  Mar 17 '12 at 15:04
  • So if (inputBx.Text = splitword[0]); btn_Click outputBx.Text = splitword[1]; or am I way off here?! –  Mar 17 '12 at 15:06
  • Why are you using splitword at all? you should be using the dictionary that you created?...Either way, best of luck with figuring out the rest – Justin Pihony Mar 17 '12 at 15:08
  • Because the file that is loaded from the streamreader should all go into the dictionary. And then I wanted the text from the file to be split so that if the first part of the string is entered into the text box and a button is pressed then the second part would go into the other text box –  Mar 17 '12 at 15:12
  • Yes, the file is loaded into the dictionary for each split. So, you should just need to do something like this: if(d.ContainsKey(inputBx.Text)){outputBx.Text = d[inputBx.Text]} Unless I am missing something, that is. As I had said before, best of luck with figuring the rest of your problem. I am not sure why you took away the checkmark, but this answers your immediate question. If you need another question answered, please submit a new question. – Justin Pihony Mar 17 '12 at 19:45
  • 1
    @user1274876 Might I ask why the accept checkmark was removed? I thought you said this solved your need? – Justin Pihony Mar 18 '12 at 03:32
0

The thing with a Dictionary's TryGetValue() method is that it really comes into its own only when the value of the dictionary entry is a reference type that's being used as some sort of accumulator or is being transformed somehow :

public Dictionary<string,List<Widget>> LoadWidgetDictionary( IEnumerable<Widget> widgets )
{
  Dictionary<string,List<Widget>> instance = new Dictionary<string,List<Widget>>() ;

  foreach( Widget item in widgets )
  {
    List<Widget> accumulator ;
    bool         found       = instance.TryGetValue( item.Name , out accumulator ) ;

    if ( !found )
    {
      accumulator = new List<Widget>() ;
      instance.Add( item.Name , accumulator ) ;
    }

    accumulator.Add(item) ;

  }

  return ;
}

If you're not doing that, you're probably better off just checking to see if the key is found in the dictionary:

public Dictionary<string,Widget> LoadWidgets( IEnumerable<Widget> widgets )
{
  Dictionary<string,Widget> instance = new Dictionary<string,Widget>() ;

  foreach ( Widget item in widgets )
  {
    if ( instance.ContainsKey( item.Name ) )
    {
      DisplayDuplicateItemErrorMessage() ;
    }
    else
    {
      instance.Add( item.Name , item ) ;
    }
  }
  return instance ;
}

Amended to add a suggestion

You might try something like:

Dictionary<string,string> LoadDictionaryFromFile( string fileName )
{
  Dictionary<string,string> instance = new Dictionary<string,string>() ;

  using ( TextReader tr = File.OpenText( fileName ) )
  {
    for ( string line = tr.ReadLine() ; line != null ; line = tr.ReadLine() )
    {
      string key   ;
      string value ;

      parseLine( line , out key , out value ) ;
      addToDictionary( instance , key , value );

    }
  }

  return instance ;
}

void parseLine( string line , out string key , out string value )
{
  if ( string.IsNullOrWhiteSpace(line) ) throw new InvalidDataException() ;
  string[] words = line.Split( ',' ) ;

  if ( words.Length != 2 ) throw new InvalidDataException() ;

  key   = words[0].Trim() ;
  value = words[1].Trim() ;

  if ( string.IsNullOrEmpty( key   ) ) throw new InvalidDataException() ;
  if ( string.IsNullOrEmpty( value ) ) throw new InvalidDataException() ;

  return ;
}

private static void addToDictionary( Dictionary<string , string> instance , string key , string value )
{
  string existingValue;
  bool   alreadyExists = instance.TryGetValue( key , out existingValue );

  if ( alreadyExists )
  {
    // duplicate key condition: concatenate new value to the existing value,
    // or display error message, or throw exception, whatever.
    instance[key] = existingValue + '/' + value;
  }
  else
  {
    instance.Add( key , value );
  }
  return ;
}
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • I appreciate the help, thanks. However, I've been told by my tutor that everything i've done is correct so far. It's after the string[] splitword = line.Split(','); line that I just can't figure out what's next. I don't have the option I have to use TryGetValue –  Mar 16 '12 at 21:18
  • If this is homework, you should tag it as such. However, seem my amended answer for a suggestion. – Nicholas Carey Mar 16 '12 at 21:21
  • It isn't homework, my tutor is the guy who recommended this website for additional help! –  Mar 16 '12 at 21:24
  • I still don't understand though, I was told I just need an extra line or two of code underneath what I've done to finish off the split and assign [1] or [0] to the string –  Mar 16 '12 at 21:27