New to C# Trying to figure out how to create an array from an exisitng .txt file. Call text file "filename" File contains pairs of elements separated by coma such as:
AGT, H
ATT, M
TAA, J
AAG, I
Eventually I need to pair these up again in a dictionary, but I don't think I need to use a 2D array, unless it's easier.
Any suggestions???
All ideas and advice is welcomed as I am new to C# and needing to learn VERY quickly.
Thank you!!
Use string.Split to get a string[] from the columns. Then you could get a IEnumerable<string[]> in this way:
var lines = File.ReadLines(l => l.Split(','));
If you want to materialize the query to a collection you could use ToList or ToArray:
List<string[]> lineList = lines.ToList();
If you want to create a Dictionary<string, string> instead (duplicate keys are not allowed):
var dict = lines.Select(l => l.Split(','))
.ToDictionary(split => split.First(), split => split.Last());
You can read the lines, split each line into an array with two items, then fill a dictionary from it:
Dictionary<string, string> dict =
File.ReadLines(filename)
.Select(l => l.Split(new string[]{", "}, StringSplitOptions.None))
.ToDictionary(p => p[0], p => p[1]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With