Hi,

I am new to c# and I am trying to read a file which is of format:

1 2 3
3 4 5
6 7 8

1 2
3 4

the problem is I am not able to read file in given format, I am not able to tell the streamReader to read separately. Like for example if I ask to read till end of file I can't seperate the format altogether. I have to store first format in different arrays and the other format into different arrays for example:
arrayList A will store 1,3,6
arrayList B will store 2,4,7
arrayList C will store 3,5,8

and 2 other arrays will store
arrayList D will store 1,3
arrayList f will store 2,4

I tried to search it but I didn't got any success till now.
some code that I tried was:

StreamReader myFile = new StreamReader(fileInputTextBox.Text);
   //Reads the file line by line
  while (!myFile.EndOfStream)
    {
        string myString = myFile.ReadLine(); //reads file line by line
         fillArray(myString);
     }
    myFile.Close();

This is the code I am using to read file, since I don't know how to make the streamReader read till my format change I am just reading till end of stream.
another method that I use to store it into an array:

public void formArray(string fileString)
        {
            string filestring=fileString;
            string[] tokens = new string[3];
            tokens =filestring.Split(' '); //split string with delimiter as space
            A.Add(tokens[0]);
            B.Add(tokens[1]);
            C.Add(tokens[2]);
          //don't know how to work for D and F 
         }

I am really confused can anyone suggest how can I do that.

Thanks!!

Is the data structure static in that it will always be in the format exampled?

You could check tokens.Length and then act accordingly.
Should also advise you to use the generic List<> type instead of ArrayList.

This is an odd task. As danny pointed out the generic list is definetly the way to go! You could do something like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace daniweb
{
  public partial class frmWeirdHomework : Form
  {
    public frmWeirdHomework()
    {
      InitializeComponent();
    }

    private static string[] GetSampleData()
    {
      List<string> sl = new List<string>();
      sl.Add("1 2 3");
      sl.Add("3 4 5");
      sl.Add("6 7 8");
      sl.Add("");
      sl.Add("1 2 ");
      sl.Add("3 4 ");
      return sl.ToArray();
    }

    private static bool IsNumericArray(string[] arr)
    {
      if ((arr == null) || (arr.Length == 0))
        return false;

      int i;

      foreach (string s in arr)
      {
        if (!int.TryParse(s, out i))
          return false;
      }
      return true;
    }

    private void button2_Click(object sender, EventArgs e)
    {
      //string[] data = File.ReadAllLines(@"C:\yourfile.txt");
      string[] data = GetSampleData();
      List<List<int>> lstAllItems = new List<List<int>>(); //master list
      
      List<List<int>> workingSet = new List<List<int>>(); //holds our working lists until the format changes

      foreach (string line in data)
      {
        if (string.IsNullOrEmpty(line))
          continue;
        string[] sVals = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (!IsNumericArray(sVals))
          continue;

        int[] iVals = Array.ConvertAll<string, int>(sVals, Convert.ToInt32);
        if (workingSet.Count != iVals.Length) //our format changed
        {
          lstAllItems.AddRange(workingSet.ToArray());
          workingSet.Clear();
          for (int i1 = 0; i1 < iVals.Length; i1++)
          {
            workingSet.Add(new List<int>());
          }
        }
        for (int i1 = 0; i1 < iVals.Length; i1++)
        {
          workingSet[i1].Add(iVals[i1]);
        }
      }
      if (workingSet.Count != 0)
        lstAllItems.AddRange(workingSet.ToArray());
      

      for (int i1 = 0; i1 < lstAllItems.Count; i1++)
      {
        List<int> lst = lstAllItems[i1];
        Console.WriteLine("Array[{0:F0}]: {1}", i1, string.Join(", ", lst.ConvertAll<string>(Convert.ToString).ToArray()));
      }
    }

  }
}
Array[0]: 1, 3, 6
Array[1]: 2, 4, 7
Array[2]: 3, 5, 8
Array[3]: 1, 3
Array[4]: 2, 4

I'm sure you can figure out how to make 0->A, 1->B, etc :)

You could check tokens.Length and then act accordingly.
Should also advise you to use the generic List<> type instead of ArrayList.

Thanks a lot for the advice. It worked out. I thought if you do not specify array size while you initialize it gives error but it didn't gave a error. Can you tell me why you asked me to used list instead of arraylist. what's the advantage? It might be silly question but I really wanna know.

This is an odd task. As danny pointed out the generic list is definetly the way to go! You could do something like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace daniweb
{
  public partial class frmWeirdHomework : Form
  {
    public frmWeirdHomework()
    {
      InitializeComponent();
    }

    private static string[] GetSampleData()
    {
      List<string> sl = new List<string>();
      sl.Add("1 2 3");
      sl.Add("3 4 5");
      sl.Add("6 7 8");
      sl.Add("");
      sl.Add("1 2 ");
      sl.Add("3 4 ");
      return sl.ToArray();
    }

    private static bool IsNumericArray(string[] arr)
    {
      if ((arr == null) || (arr.Length == 0))
        return false;

      int i;

      foreach (string s in arr)
      {
        if (!int.TryParse(s, out i))
          return false;
      }
      return true;
    }

    private void button2_Click(object sender, EventArgs e)
    {
      //string[] data = File.ReadAllLines(@"C:\yourfile.txt");
      string[] data = GetSampleData();
      List<List<int>> lstAllItems = new List<List<int>>(); //master list
      
      List<List<int>> workingSet = new List<List<int>>(); //holds our working lists until the format changes

      foreach (string line in data)
      {
        if (string.IsNullOrEmpty(line))
          continue;
        string[] sVals = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (!IsNumericArray(sVals))
          continue;

        int[] iVals = Array.ConvertAll<string, int>(sVals, Convert.ToInt32);
        if (workingSet.Count != iVals.Length) //our format changed
        {
          lstAllItems.AddRange(workingSet.ToArray());
          workingSet.Clear();
          for (int i1 = 0; i1 < iVals.Length; i1++)
          {
            workingSet.Add(new List<int>());
          }
        }
        for (int i1 = 0; i1 < iVals.Length; i1++)
        {
          workingSet[i1].Add(iVals[i1]);
        }
      }
      if (workingSet.Count != 0)
        lstAllItems.AddRange(workingSet.ToArray());
      

      for (int i1 = 0; i1 < lstAllItems.Count; i1++)
      {
        List<int> lst = lstAllItems[i1];
        Console.WriteLine("Array[{0:F0}]: {1}", i1, string.Join(", ", lst.ConvertAll<string>(Convert.ToString).ToArray()));
      }
    }

  }
}
Array[0]: 1, 3, 6
Array[1]: 2, 4, 7
Array[2]: 3, 5, 8
Array[3]: 1, 3
Array[4]: 2, 4

I'm sure you can figure out how to make 0->A, 1->B, etc :)

I am really thankful for such a nice example. But I wouldlike to ask the same question to you as well. why we are using list instead of arraylist? Please can you give some brief explanation?

Hello.
Both ArrayList and List classes are provided to work with dynamic arrays. But, in ArrayList all elements have type of System.Object. And in List you specify the type of elements by yourself. Let's see what it gives to you:

1. Suppose, you have an array of strings.
For ArrayList: while adding new element to array - it will be
cast to an Object type and then added to list. Then to take the
value of it - you'd have to cast it back to String.

ArrayList list = new ArrayList();
            list.Add("String element");

            string element = (string)list[0];

For List: you're just define a List of strings and there's no need
in boxing/unboxing operations (casting to Object type and back).

List<string> otherList = new List<string>();
            otherList.Add("String element");
            string otherElement = otherList[0];

2. Since the every reference type can be cast to System.Object and every value type can be boxed into an Object, it's possible to have something like this (in ArrayList):

ArrayList list = new ArrayList();
            list.Add("String element");
            list.Add(2);

The List<T> is strong-typed, so it's one more advantage. E.g. it wouldn't allow you to add Integer in your list of Strings. You will be warned at compilation time that you're trying to do something illegal.

List<string> otherList = new List<string>();
            otherList.Add("String element");
            otherList.Add(2); // compilation time error

3. And here's a nice post, where performance of List And ArrayList was compared: ArrayList’s vs. generic List for primitive types and 64-bits

commented: Great explanation +17
commented: Nice and clear explanation :) +14

Hello.
Both ArrayList and List classes are provided to work with dynamic arrays. But, in ArrayList all elements have type of System.Object. And in List you specify the type of elements by yourself. Let's see what it gives to you:

1. Suppose, you have an array of strings.
For ArrayList: while adding new element to array - it will be
cast to an Object type and then added to list. Then to take the
value of it - you'd have to cast it back to String.

ArrayList list = new ArrayList();
            list.Add("String element");

            string element = (string)list[0];

For List: you're just define a List of strings and there's no need
in boxing/unboxing operations (casting to Object type and back).

List<string> otherList = new List<string>();
            otherList.Add("String element");
            string otherElement = otherList[0];

2. Since the every reference type can be cast to System.Object and every value type can be boxed into an Object, it's possible to have something like this (in ArrayList):

ArrayList list = new ArrayList();
            list.Add("String element");
            list.Add(2);

The List<T> is strong-typed, so it's one more advantage. E.g. it wouldn't allow you to add Integer in your list of Strings. You will be warned at compilation time that you're trying to do something illegal.

List<string> otherList = new List<string>();
            otherList.Add("String element");
            otherList.Add(2); // compilation time error

3. And here's a nice post, where performance of List And ArrayList was compared: ArrayList’s vs. generic List for primitive types and 64-bits

Hey, thanks a lot!! I really get a good idea now why not to use arraylist when it is a better idea using list. That was a nice explanation.:)

You're welcome :)
Good luck with learning C#.

Please, mark this thread as solved if the issue is settled.

commented: Spiritually optimized....Awesome!--jk, good job! +4

>> Antenka
Great explanation :)

Please mark this thread as solved if you have found an answer to your question and good luck!

Anteka, very good reply! I had to look up the SOS (Spiritually Optimized System) acronym though--LOL.

Thanks, guys :)
Hehe .. Spiritually Optimized .. interesting thingy :P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.