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"
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);