简体   繁体   中英

How do i create a c# dictionary that will read in key and values from .csv file

I have a .csv file with a list of abbreviations and their actual meaning eg

Laughing Out Loud, LOL

I need to be able to search for an abbreviation in a text box and replace the abbreviation with the actual words. This is what I have attempted so far to understand dictionaries but cannot work out how to read in values from the file.

 Dictionary<string, string> Abbreviations = new Dictionary<string, string>();
 Abbreviations.Add("Laughing Out Loud", "lol");
 foreach (KeyValuePair<string, string> abbrev in Abbreviations)
 {
     txtinput.Text = txtinput + "<<" + abbrev.Key + ">>";
 }

You can start by creating a Stream Reader for your file, then looping for all your values in the CSV and add them to the dictionary.

static void Main(string[] args)
{
    var csv_reader = new StreamReader(File.OpenRead(@"your_file_path"));

    //declare your dictionary somewhere outside the loop.

    while (!csv_reader.EndOfStream)
    {
       //read the line and split if you need to with .split('')
        var line = reader.ReadLine();           

       //Add to the dictionary here

    }

   //Call another method for your search and replace. 
   SearchAndReplace(your_input)
}

Then have the implementation of that method, search if the input exists in the dictionary and if it does replace it.

You could use LINQ to put the values of the csv into your dictionary, if that's easier for you.

You can try this LINQ solution the GroupBy is to handle the case where a key is in a file multiple times.

  Dictionary<string, string[]> result =
     File.ReadLines("test.csv")
    .Select(line => line.Split(','))
    .GroupBy(arr => arr[0])
    .ToDictionary(gr => gr.Key,
                  gr => gr.Select(s => s[1]).ToArray());

To check if the abbreviation in the TextBox exists in the Dictionary :

foreach (KeyValuePair<string, string[]> abbrev in result)
{
    if (txtinput.Text == abbrev.Value)
    {
        txtinput.Text = txtinput + "<<" + abbrev.Key + ">>";
    }
}

I'm going to assume that your input file may have commas in the actual text, and not just separating the two fields.

Now, if that were the case, then the standard CSV file format for format the file like this:

Laughing Out Loud,LOL
"I Came, I Saw, I Conquered",ICISIC

However, from your example you have a space before the "LOL", so it doesn't appear that you're using standard CSV.

So I'll work on this input:

Laughing Out Loud, LOL
"I Came, I Saw, I Conquered",ICISIC
"to, too, or two", 2
because,B/C

For this input then this code produces a dictionary:

var dictionary =
(
    from line in File.ReadAllLines("FILE.CSV")
    let lastComma = line.LastIndexOf(',')
    let abbreviation = line.Substring(lastComma + 1).Trim()
    let actualRaw = line.Substring(0, lastComma).Trim()
    let actual = actualRaw.StartsWith("\"") && actualRaw.EndsWith("\"")
        ? actualRaw.Substring(1, actualRaw.Length - 2)
        : actualRaw
    select new { abbreviation, actual }
).ToDictionary(x => x.abbreviation, x => x.actual);

字典

You can go one better than this though. It's quite possible to create a "super function" that will do all of the replaces in one go for you.

Try this:

var translate =
(
    from line in File.ReadAllLines("FILE.CSV")
    let lastComma = line.LastIndexOf(',')
    let abbreviation = line.Substring(lastComma + 1).Trim()
    let actualRaw = line.Substring(0, lastComma).Trim()
    let actual = actualRaw.StartsWith("\"") && actualRaw.EndsWith("\"")
        ? actualRaw.Substring(1, actualRaw.Length - 2)
        : actualRaw
    select (Func<string, string>)(x => x.Replace(abbreviation, actual))
).Aggregate((f1, f2) => x => f2(f1(x)));

Then I can do this:

Console.WriteLine(translate("It was me 2 B/C ICISIC, LOL!"));

I get this result:

It was me to, too, or two because I Came, I Saw, I Conquered, Laughing Out Loud!

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