Solved

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

Posted on 2010-09-18
10
222 Views
Last Modified: 2012-05-10
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
     PrintObjectVariableContentAndPrintWholeArrayListContentSaveWholeArrayListContentInVariable
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

0
Comment
Question by:ashley2009
  • 7
  • 3
10 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33709945
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

0
 
LVL 3

Author Comment

by:ashley2009
ID: 33709960
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.
0
 
LVL 3

Author Comment

by:ashley2009
ID: 33709968
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.
0
Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 33709975
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

0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 33709978
On second thought, I don't think you need the "new string(o)" part. It can instead be "o.ToString()":
for (int k = 0; k <= list.Count; k++)
{
    if (list[k] is char[])
    {
        foreach (object o in list[k])
        {
            Console.WriteLine(o.ToString());
        }
    }
    else
    {
        Console.WriteLine(list[k].ToString());
    }
}

Open in new window

0
 
LVL 3

Author Comment

by:ashley2009
ID: 33710019
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?

0
 
LVL 3

Author Comment

by:ashley2009
ID: 33710039
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.
0
 
LVL 3

Author Comment

by:ashley2009
ID: 33710053
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.
0
 
LVL 3

Author Comment

by:ashley2009
ID: 33710180
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

0
 
LVL 3

Author Comment

by:ashley2009
ID: 33710267
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

0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
asp day pilot 3 19
Javascript to set controls visibility 5 36
Hey Audio! 3 29
Release Dynamically Allocated Memory in C# 3 26
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.

778 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question