ディクショナリのメソッドの特徴は、ディクショナリ エントリの値が、ある種のアキュムレータとして使用されているか、何らかの方法で変換されている参照型である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 ;
}