0

さて、私はどこでも検索しましたが、本当にこれにこだわっています. ストリームリーダーを使用してコンマで区切られたテキスト単語を含む CSV ファイルをロードし、それらを辞書に追加するプログラムを作成しようとしています。次に、ユーザーがカンマの前のテキストを最初のテキスト ボックスに入力してボタンをクリックすると、フォーム上でカンマの後のテキストが他のテキスト ボックスに表示されます。

私は嘘をつくつもりはありません。私はまだC#の基本を学ぼうとしているので、説明された答えをいただければ幸いです。

これは私のコードであり、ここからどこに行くべきかわかりません。コンマ分割の後に TryGetValue を使用して、テキストの最初の部分を [0] として割り当て、コンマの後の 2 番目の部分を [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(',');
            }
        }
    }
}

私の入力データの例は次のようなものです:

黒、白

猫、犬

黄、青

4

2 に答える 2

0

ディクショナリのメソッドの特徴は、ディクショナリ エントリのが、ある種のアキュムレータとして使用されているか、何らかの方法で変換されている参照型であるTryGetValue()場合にのみ、実際に独自のものになるということです。

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 ;
}

そうしない場合は、キーが辞書にあるかどうかを確認するだけのほうがよいでしょう。

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 ;
}

提案を追加して修正

次のようなものを試すことができます。

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 ;
}
于 2012-03-16T21:15:35.553 に答える
0

今のところ、以下のような簡単なことをするだけです:

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);

私はコンパイルの前にいないので、これをクリーンアップする必要があるかもしれませんが、かなり近いはずです。

于 2012-03-16T20:34:03.430 に答える