C#, используя TryGetValue после разделения строки
Хорошо, я искал ВЕЗДЕ, и я действительно застрял с этим. Я пытаюсь создать программу, которая будет загружать файл CSV с текстовыми словами, разделенными запятой, с помощью потокового считывателя, а затем добавлять их в словарь. Затем в форме, если пользователь вводит текст перед запятой в первое текстовое поле и нажимает кнопку, тогда текст после запятой будет отображаться в другом текстовом поле.
Я не собираюсь лгать, я все еще пытаюсь научиться основам C#, поэтому я буду благодарен за объясненный ответ!
Это мой код только сейчас, и я не знаю, куда идти дальше. Я хочу использовать TryGetValue после разделения запятой, чтобы назначить первую часть текста как [0], а вторую часть после запятой как [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(',');
}
}
}
}
Пример моих входных данных:
черно-белый
Котопес
желтый, синий
2 ответа
Я бы просто сделал что-то простое, как показано ниже:
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);
Я не перед компиляцией, так что, возможно, это нужно очистить, но должно быть довольно близко.
Вещь со словарем 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 ;
}