C# Read file as Key value Dictionary pair

Today in this article, we will see how to Read files as Key value Dictionary pairs using a simple and effective approach.

Using this approach you can generate a Dictionary list of possible values.

To keep it simple we will use the below file where we have content separated by pipe delimiter.

However, the below-discussed approach can be used for other separator like comma-separated values(,) or space( ) or any other separator, etc.

Sample file

Below is a sample code of how we can read the content and create a dictionary of key values pair using Employee ID as Key and Employee Name as Value.

Below fileLineReader is each line from the target file. It read the content and split the data using the “I” pipe delimiter.

File with Pipe Delimiter

                   string[] keyvalue = fileLineReader.Current.Split('|');
                    if (keyvalue.Length == 3)
                    {
                        employeeDict.Add(keyvalue[1], keyvalue[0]);
                    }

Below sample code using File Emuerator

C Read file as Key value Dictionary
Csharp Dictionary how to read keyvalue from file C Read file as Key value Dictionary pair

Parse File line with Space

string[] keyvalue = fileLineReader.Current.Split(' ');
                    if (keyvalue.Length == 3)
                    {
                        employeeDict.Add(keyvalue[1], keyvalue[0]);
                    }

Parse File line with comma-separated values

string[] keyvalue = fileLineReader.Current.Split(' ');
                    if (keyvalue.Length == 3)
                    {
                        employeeDict.Add(keyvalue[1], keyvalue[0]);
                    }

Are you dealing with a huge file that needs chunking logic to be used due to its size?

If you have a huge file size to deal with then it’s important to check the performance of the filter or query.

Kindly check below 2-3 approaches discussed below for effective chunking and converting the file into a dictionary.

Kindly visit below a few useful articles on dealing with file size,

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *