Link to home
Start Free TrialLog in
Avatar of ashley2009
ashley2009

asked on

How to print object, and how to store arraylist's content in a variable using .NET C#?

Hello,

I have two questions on printing an ArrayList's content and also printing the content of an Object type variable. Please see the code section where the two methods are posted.

> Method #1 is trying to print the object variable's content but can only print
System.String[]

1) My question is how to print the object variable's content?

> Method #2 is trying to print and also to store the whole arrayList's content in a variable, but cannot as the arrayList's each index has subindexes.

2) How to print the whole arrayList's content? How to store the whole arrayList's content in a variable?

Please help. I have tried for a long time and did research, but I cannot find any ways.

And also if you have any suggestion for method # 2, where I am utilizing ArrayList to save strings as they get parsed, please let me know. Please let me know whether  List<t> should be used instead of ArrayLIST; If so, how as I have tried LIST<string> today and had problem printing the content of the LIST<string> or saving the values of the <LIST>, after it got populated, in a variable.

**If you provide code or web example, please provide in C# code as I have hard time understanding VB codes
**Please provide code sample, web link as well as your suggestions
     User generated image
Method#1: Using Object to save parsed lines
.................................................
  class ReadFilesByUsingLINQ
    {
        public ReadFilesByUsingLINQ() { }
        public object ReadFileContent(string fileName, string delim, bool flag)
        {
            System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); string elapsedMilliSecs, totalMilliSecs, elapsedTicks = null;
            object obj = null; char[] charDelim = delim.ToCharArray(); int count = 0;

            try
            {
                if ((count= (from line in File.ReadAllLines(fileName) select line).Count()) > 0)
                {
                    StreamReader sr = new StreamReader(fileName);
                    var t1 = from line in File.ReadAllLines(fileName) select line;
                    
                    foreach (var t2 in t1)
                    {
                        obj += t2; 
                    }
                    obj = (object)obj.ToString().Split(charDelim, '\n'); 
                    sw.Stop();
                }
                Console.WriteLine(obj);
                elapsedMilliSecs = sw.ElapsedMilliseconds.ToString(); totalMilliSecs = sw.Elapsed.TotalMilliseconds.ToString(); elapsedTicks = sw.ElapsedTicks.ToString();
                LogFile lg = new LogFile();
                lg.WriteInLogFile(sw.ElapsedMilliseconds.ToString(), sw.Elapsed.TotalMilliseconds.ToString(), sw.ElapsedTicks.ToString(), "LINQ", count);
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }
            return obj;
        }
    }

=====================================================================
Method#2: Using ArrayList to save parsed lines
................................................
 public void ReadFileContent(string fileName, string delim, bool flag)
        {
            System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
            string elapsedMilliSecs, totalMilliSecs, elapsedTicks = null; string line = null; ArrayList list = new ArrayList();
            string myStr = ""; System.Text.StringBuilder sb = new System.Text.StringBuilder(); int i = 0;
            try
            {
                StreamReader sr = new StreamReader(fileName);
                while ((line = sr.ReadLine()) != null)
                {
                    if (flag == true)
                    {
                        list.Add(line.Split(new char[] { ',' }));
                    }
                    else
                    {
                        list.Add(line);
                    }
                }

                for (int k = 0; k <= list.Count; k++)
                {
                    Console.WriteLine(list[k].ToString());
                }
                sw.Stop();
                int lineNum = list.Count;
                elapsedMilliSecs = sw.ElapsedMilliseconds.ToString(); totalMilliSecs = sw.Elapsed.TotalMilliseconds.ToString(); elapsedTicks = sw.ElapsedTicks.ToString();
                LogFile lg = new LogFile();
                lg.WriteInLogFile(sw.ElapsedMilliseconds.ToString(), sw.Elapsed.TotalMilliseconds.ToString(), sw.ElapsedTicks.ToString(), "LIST", lineNum);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

Open in new window

Avatar of kaufmed
kaufmed
Flag of United States of America image

In line 23, you store the results of split into "obj". Split returns an array and the default implementation of ToString() on an array prints its type. Since you are dealing with an array, you need to loop through it. The same goes for your second code sample. Here is an example:
Console.WriteLine(obj);

  becomes

foreach (object o in obj)
{
    Console.WriteLine(o.ToString());
}

Open in new window

Avatar of ashley2009
ashley2009

ASKER

Thank you for your answer; however, I still cannot print and I have tried the foreach way of printing today.

> For method one, by using your code

foreach (object o in obj)
{
                    Console.WriteLine(o.ToString());
}

the compile error is:

foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

> For method # 2, by using the below code

foreach (List<string> l in list)
{
                    Console.WriteLine(l.ToString());
}

the run time error, System Exception is:

Unable to cast object of type 'System.String[]' to type 'System.Collections.Generic.List`1[System.String]'.


Would you please suggest what code to use because I cannot locate anything as of now.
Hello,

I am very sorry as your suggestion worked for method # 1.

foreach (object o in (IEnumerable<Object>)obj)
                {
                    Console.WriteLine(o.ToString());
                }

I can print the object's content now. The method # 1 is working, please note. If you can please suggest and mean while  I also try to see whether IEmumerable solves the ArrayList problem of method#1

Thank you.
The problem is that you are storing two different object types:  char[] and string. Outside of restructuring your code, the simplest way I can see would be to do the following:
for (int k = 0; k <= list.Count; k++)
{
    if (list[k] is char[])
    {
        foreach (object o in list[k])
        {
            Console.WriteLine(new string(o));
        }
    }
    else
    {
        Console.WriteLine(list[k].ToString());
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hello,

I am trying to print the arraylist's content by using your code, but I cannot print. I think, by seeing the exceptions, that it is not printing anything as the arraylist is multidimensional: has two dimension.

What do you think? What should i do? If my assumption is true that I cannot print the ArrayList as it is multidimensional, what are the ways to print a multidimensional array?

I found a way, which is

 for (int k = 0; k < 2; k++)
                {
                    for (int j = 0; j < 2; j++)
                    {
                        o =  ((object[])list[k])[j];
                    }
                }


However, it is definitely not giving correct result as

1) I cannot figure out how to get the count of inner index
2) I cannot do
 o +=  ((object[])list[k])[j];
as o is a type object,

but atleast I can get some data from the arraylist in the object.
If you have suggestion on getting the inner index, let me know.
If you have suggestion on adding new elements in a variable

like o+=

let me know

I am also trying in the mean time and will keep posted.
By Using StringBuilder,

I can now add additional strings, but still cannot get all the inner values as I cannot figure out how to get the count of inner array of the arraylist.

System.Text.StringBuilder sa = new System.Text.StringBuilder();
                for (int k = 0; k < list.Count; k++)
                {
                    for (int j = 0; j < list.Count; j++)//How to get the count of the inner array?
                    {
                        sa.Append(((object[])list[k])[j].ToString());
                    }
                }
               
If you know, please let me know.
Hi,

I solved the problem of method# 2 by not using ArrayList but using List<t>. The complete class is at below.

I wanted to use ArrayList but I was not able to get the count of inner array of the arraylist ( here it is a two dimensional array), and therefore, I was not able to print the inner values as the program was throwing exception.

Well, I will keep this question open in case anyone can tell how to get the count number of the inner array as I cannot find any information of getting the count of inner array of arraylist when the arraylist is constructed the way i constructed. If it were an int arraylist, there would be no problem to get the count of inner array of arraylist, but it is a string arraylist.

I hope that someone will provide information.

 class ReadFilesUSINGLIST
    {
        public ReadFilesUSINGLIST() { }
        public void ReadFileContent(string fileName, string delim, bool flag)
        {
            System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
            string elapsedMilliSecs, totalMilliSecs, elapsedTicks = null; string line = null; List<string> list = new List<string>();

            System.Text.StringBuilder sb = new System.Text.StringBuilder(); var myVar = ""; object _object = null;
            try
            {
                StreamReader sr = new StreamReader(fileName);
                while ((line = sr.ReadLine()) != null)
                {
                  
                    if (flag == true)
                    {
                        list.Add(line);
                    }
                    else
                    {
                        list.Add(line);
                    }
                }
              
                System.Text.StringBuilder sa = new System.Text.StringBuilder();
                foreach (object o in (IEnumerable<Object>)list)
                {
                   sa.Append(o.ToString().Replace(',', '\n'));
                   myVar += o.ToString().Replace(',', '\n');
                   _object += o.ToString().Replace(',', '\n');
                }

                    Console.WriteLine(sa+"\n......................\n");
                    Console.WriteLine(myVar+"\n.............................\n");
                    Console.WriteLine(_object + "\n.............................\n");
              
                sw.Stop();
                int lineNum = list.Count;
                
                elapsedMilliSecs = sw.ElapsedMilliseconds.ToString(); totalMilliSecs = sw.Elapsed.TotalMilliseconds.ToString(); elapsedTicks = sw.ElapsedTicks.ToString();
                LogFile lg = new LogFile();
                lg.WriteInLogFile(sw.ElapsedMilliseconds.ToString(), sw.Elapsed.TotalMilliseconds.ToString(), sw.ElapsedTicks.ToString(), "LIST", lineNum);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

Open in new window

I was also able to solve the problem by using arraylist ( without having an inner array inside the arrayList); i can now print and save arraylist's content.

StreamReader sn = new StreamReader(fileName);
line = null;ArrayList strsList = new ArrayList();
while ((line = sn.ReadLine()) != null)
{
    string[] strs = line.Split(',');
    foreach (string s in strs)
        strsList.Add(s);
}
Console.WriteLine("Using ArrayList DataType and saving it in an object type:\n\n");
 object arrList=null;
foreach (string s in strsList)
{
   // Console.WriteLine(s);
    arrList += s+"\n";
}
Console.WriteLine(arrList);

I will keep the question open for 12 hours if in any case people like to discuss or give solution for thread # 09/18/10 08:30 PM, ID: 33710053, which is how to get the inner array's count of an arraylist.

The whole working class is attached.


//One of Way of Reading File using LIST or Array LIST
    class ReadFilesUSINGLIST
    {
        public ReadFilesUSINGLIST() { }
        public void ReadFileContent(string fileName, string delim, bool flag)
        {
            System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
            string elapsedMilliSecs, totalMilliSecs, elapsedTicks = null; string line = null; List<string> list = new List<string>();
            System.Text.StringBuilder sb = new System.Text.StringBuilder(); var myVar = ""; object _object = null; 
            try
            {
                StreamReader sr = new StreamReader(fileName);
                while ((line = sr.ReadLine()) != null)
                {
                    if (flag == true)
                    {
                        list.Add(line);
                        list.Add("\n");
                    }
                    else
                    {
                        list.Add(line);
                    }
                }
StreamReader sn = new StreamReader(fileName);
line = null;ArrayList strsList = new ArrayList();
while ((line = sn.ReadLine()) != null)
{
    string[] strs = line.Split(',');
    foreach (string s in strs)
        strsList.Add(s);
}
Console.WriteLine("Using ArrayList DataType and saving it in an object type:\n\n"); 
 object arrList=null;
foreach (string s in strsList)
{
   // Console.WriteLine(s);
    arrList += s+"\n";
}
Console.WriteLine(arrList);

Console.WriteLine("\n------------------------------------------\n");

                System.Text.StringBuilder sa = new System.Text.StringBuilder();
                foreach (object o in (IEnumerable<Object>)list)
                {
                   
                   sa.Append(o.ToString().Replace(',', '\n'));
                   
                   myVar += o.ToString().Replace(',', '\n');
                   
                   _object += o.ToString().Replace(',', '\n');
                }
                    Console.WriteLine("\nStringBuilder:\n");
                    Console.WriteLine(sa+"\n......................\n");
                    Console.WriteLine("\nVar DataType:\n");
                    Console.WriteLine(myVar+"\n.............................\n");
                    Console.WriteLine("\nObject DataType:\n");
                    Console.WriteLine(_object + "\n.............................\n");
              
                sw.Stop();
                int lineNum = list.Count;
                
                elapsedMilliSecs = sw.ElapsedMilliseconds.ToString(); totalMilliSecs = sw.Elapsed.TotalMilliseconds.ToString(); elapsedTicks = sw.ElapsedTicks.ToString();
                LogFile lg = new LogFile();
                lg.WriteInLogFile(sw.ElapsedMilliseconds.ToString(), sw.Elapsed.TotalMilliseconds.ToString(), sw.ElapsedTicks.ToString(), "LIST", lineNum);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

Open in new window