Reputation: 43
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!!
Upvotes: 2
Views: 6701
Reputation: 921
Use ReadAllLines(String)
.
Reference: http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx
Upvotes: 1
Reputation: 700152
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]);
Upvotes: 1
Reputation: 460018
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());
Upvotes: 7
Reputation: 3243
You can read the file into a dictionary using some LINQ :)
File.ReadLines(path)
.Select(l => l.Split(','))
.ToDictionary(k => k[0], v => v[1]);
Upvotes: 0