C # multidimensional arrays like PHP

I try to do this for about 6 hours, and I'm at a standstill.

I want the equivalent of this in C #:

$settings = array(); foreach(file('settings.txt') as $l) $settings[]=explode(',',$l); print $settings[0][2]; 

This is what still does not work for me:

 string fileName = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\" + "settings.txt"; string[,] settings; FileStream file = null; StreamReader sr = null; try { file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read); sr = new StreamReader(file, Encoding.ASCII); string[] line; int i = 0; do { line = sr.ReadLine().Split(','); settings[i++, 0] = line[0]; } while (line != null); file.Close(); MessageBox.Show(settings[1, 0]); } catch (Exception err) { MessageBox.Show(err.Message); } 

I get a "Link to an object not set to an instance of the object", any ideas would be appreciated.

+4
source share
6 answers

Use a jagged array instead of a multidimensional one - or better yet, List<string[]> :

 var settings = new List<string[]>(); foreach (string line in File.ReadLines("settings.txt", System.Text.Encoding.ASCII)) settings.Add(line.Split(',')); 

Using LINQ LINQ instead of a loop is a good alternative.

+7
source

First you must initiate your array as follows:

 string[,] settings = new string[3,3]; 

EDIT: Also on this line you will skip to set the first element of the array:

 settings[i++, 0] = line[0]; 

You must assign your value as follows:

 settings[i, 0] = line[0]; i++; 
+3
source

If you are going to look at a lot of different cells:

  string[][] lines = File.ReadAllLines(path).Select( line => line.Split(',').ToArray()).ToArray(); Console.WriteLine(lines[0][2]); 

If you only want [0] [2], you can limit it a bit ...

  using (StreamReader sr = File.OpenText(path)) { // only read the first line (zero) Console.WriteLine(sr.ReadLine().Split(',')[2]); } 
+3
source

Well, it doesn't even need to be compiled - you never initialize the settings value. Arrays in .NET have a fixed size - it seems to me that you should use List<string[]> instead:

 List<string> settings = new List<string>(); using (TextReader reader = File.OpenText(fileName, Encoding.ASCII)) { string line; while ((line = reader.ReadLine()) != null) { settings.Add(line.Split(',')); } } MessageBox.Show(settings[1][0]); // Shows the first part of the second line 

(Note that this also ensures that the file is closed even if exceptions occur - you should definitely learn about the using statement. Marc's solution avoids this by loading all the lines in one call, which obviously has memory overhead, but otherwise it's good.)

+3
source

Thanks for the super quick answers !!

I decided:

 List settings = new List(); foreach (string line in File.ReadAllLines("settings.txt", System.Text.Encoding.ASCII)) settings.Add(line.Split(',')); 

Thanks!

Dean.

0
source

There was a code-golf issue last week regarding a similar issue. And on request, I wrote a version that used LINQ. You can check it out on my website .

You probably want to adapt it a little for your needs ...

 static void Main(string[] args) { string[][] lines = null; using (var lp = "settings.txt".Load()) lines = lp.Select(l => l.Split(',')).ToArray(); } 

http://hackersbasement.com/?p=96 (and just in case, my site is ever changing)

 public static class LineProcessorLinq { public static LineProcessor Load(this string fileName) { return new LineProcessor(fileName); } public static void Write(this IEnumerable<string> lines, string header, string footer, string fileName) { using (var fs = File.AppendText(fileName)) lines.Write(header, footer, fs); } public static void Write(this IEnumerable<string> lines, string header, string footer, StreamWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); if (!string.IsNullOrEmpty(header)) writer.Write(header); foreach (var line in lines) writer.Write(line); if (!string.IsNullOrEmpty(footer)) writer.Write(footer); } } public class LineProcessor : Component, IEnumerable<string> { private StreamReader _reader = null; public LineProcessor(string fileName) : this(File.OpenText(fileName)) { } public LineProcessor(StreamReader reader) { if (reader == null) throw new ArgumentNullException("reader"); _reader = reader; } protected override void Dispose(bool disposing) { if (disposing && _reader != null) _reader.Close(); } #region IEnumerable<string> Members public IEnumerator<string> GetEnumerator() { var currentPos = _reader.BaseStream.Position; while (!_reader.EndOfStream) yield return _reader.ReadLine(); if (_reader.BaseStream.CanSeek) _reader.BaseStream.Seek(currentPos, SeekOrigin.Begin); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } #endregion } 
0
source

Source: https://habr.com/ru/post/1286345/


All Articles