Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Read Lines from File and Turn Array of Strings into Dictionary in C# with line Number as Key?

I’m trying to read lines from a file (whose size is unknown) and convert the array values that start with "A" into a Dictionary with the line number as the key and the line contents as the value. I’m trying to think of a way of doing this without iterating over the array as that would be slow for large files. I’m currently putting in the line’s hashcode (assuming no duplicates, but I can use .Distinct if needed) as the key but get an error as shown below the code:

Code:

Dictionary<int, string> lines = File
  .ReadLines(inputFilePath)
  .Select(x => x.StartsWith("A"))
  .ToDictionary(x => x.GetHashCode, x => x.ToString());

The ToDictionary has the red error line with the following message:
"The Type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In that line, I’m just trying to get some distinct value for each Key, but I would like to get the line number if possible. I feel it’s something obvious I’m missing.

>Solution :

Let’s start from the example. You have a file like this:

Abracadabra
Boo-zoo
Sausages
Alakazam

And you want to obtain a dictionay: value is a file line which starts from A,
key is 1, 2, 3, ...

{1, "Abracadabra"}
{2, "Alakazam"}

So we can do it like this:

Dictionary<int, string> lines = File
  .ReadLines(inputFilePath)
  .Where(line => line.StartsWith("A"))
  .Select((value, index) => (value, index))
  .ToDictionary(pair => pair.index + 1, pair => pair.value);

The little trick is to obtain line index which we can do with a help of Select:

  .Select((value, index) => (value, index))

If you want to use line index before filtration, i.e.

{0, "Abracadabra"}
{3, "Alakazam"}

move Select ahead:

Dictionary<int, string> lines = File
  .ReadLines(inputFilePath)
  .Select((value, index) => (value, index))
  .Where(pair => pair.value.StartsWith("A"))
  .ToDictionary(pair => pair.index + 1, pair => pair.value);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading