简体   繁体   中英

Dictionary with 2 values

That's my CSV file Test.csv:

AAA, 81, 82, *, *
BBB, 83, 84, *, *
CCC, -, 86, *, *
DDD, 87, 88, *, *
EEE, 89, 90, *, *
FFF, 99, -, -, *
GGG, 102, 108, -, *

Normally, I use this line to create a dictionary from a CSV file and check if a variable is in my dictionary:

var dictionary = File.ReadLines(@"Test.csv").Select(line => line.Split(',')).ToDictionary(data => data[0], data => data[1]);
if (dictionary.ContainsKey(variable.ToString()))
{
    var tmp = dictionary.FirstOrDefault(x => x.Key == variable.ToString()).Value;
    Description.Add(tmp);
}

But now, there are two values (eg 81, 82) for each key (eg AAA).

Does anyone have a solution for me to check the variable against both values?

I'd just create a new class or struct to encapsulate the two values. You could use Tuple<,> instead, but personally I'd create a new type so that you can use friendlier property names. You might want to include all the data from the line there, in fact... then your CSV parsing code could become something like:

var dictionary = File.ReadLines("Test.csv")
                     .Select(Entry.FromCsv) // Static method in the Entry class
                     .ToDictionary(e => e.Name);

...

// Looking up by name
Entry entry;
if (dictionary.TryGetValue(name, out entry))
{
    // Now use entry, with all the relevant properties
}

Just the simple act of encapsulating all the data from one line of the CSV file is likely to make all kinds of code that works with it easier to read.

Hope I'm following your original code... how about this.. Changes your dictionary from a <string, string> dictionary to an <string, IEnumerable<string>> dictionary. So a dictionary of collection of strings. I changed your FirstOrDefault code... it made me scratch my head too much.

var dictionary = File.ReadLines(@"Test.csv").Select(line => line.Split(',')).ToDictionary(data => data[0], data => data.Skip(1).Take(data.Count - 3));
if (dictionary.ContainsKey(variable.ToString()))
{
    var tmp = dictionary[variable.ToString()]
    foreach(string str in tmp)
       Description.Add(str);
}

This will give you a dictionary from the CSV for any number of values, assuming you don't take the last two.

如果您想拥有一个字典词典,而只是隐藏肮脏的实现细节,则可以在网上查找Trictionary的几个实现。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM