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 (e.g. 81, 82) for each key (e.g. 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.
See more on this question at Stackoverflow