Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to create array from .txt file

Tags:

arrays

c#

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!!

like image 743
novicebytes Avatar asked Dec 10 '25 21:12

novicebytes


2 Answers

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());
like image 100
Tim Schmelter Avatar answered Dec 13 '25 21:12

Tim Schmelter


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]);
like image 38
Guffa Avatar answered Dec 13 '25 21:12

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!