Dictionary 方法的问题在于,只有当字典条目的值是用作某种累加器或正在以某种方式转换的引用类型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 ;
}