Create list at runtime

Category: c# language

Question

rsbme on Sun, 16 Dec 2012 15:54:23


I'm reading lines from a text file and need to put those lines in several list<string>.  The text file is formatted as follows:

A,some#,someText

A,some#,someText

A,some#,someText

B,some#someText

B,some#,someText

etc.......

I would like every line beginning with A to go into one list, B in another list, C in yet another list, and so on.  How would I create and name the list when the program is started?  The lists will always be list<string>.  A, B, C, etc.. represent some string of characters known only at runtime.  I'm using Visual C#, 2008.

Replies

Stefan Hoffmann on Sun, 16 Dec 2012 16:08:00


Use a Dictionary<string, List<string>>.

Venkat786 on Sun, 16 Dec 2012 16:54:02


rsbme : Does this help ?

 public Form1()
        {
            InitializeComponent();
            var lines = File.ReadAllLines(@"C:\data.txt").Where(s => s != String.Empty);
            string listtoAdd = String.Empty;

            //Assumption that you have listbox already..
            //If not creates it based on your layout
            int pointy = 20;
            foreach(var line in lines)
            {
              listtoAdd=line.Substring(0, line.IndexOf(","));
              if (Controls.Find("ListBox" + listtoAdd, true).Count() > 0)
              {
                   ListBox objBox = (ListBox) Controls.Find("ListBox" + listtoAdd, true)[0];
                   objBox.Items.Add(line.Substring(line.IndexOf(",") + 1));
              }
              else
              {
                  ListBox newBox = new ListBox(); newBox.Name = "ListBox" + listtoAdd;
                  newBox.Items.Add(line.Substring(line.IndexOf(",") + 1));              
                  newBox.Location = new System.Drawing.Point(20, pointy);
          
                  pointy = pointy + 100;
              
                  this.Controls.Add(newBox);
              }
             
            }
         }
      

Mitja Bonca on Sun, 16 Dec 2012 17:52:55


Create a custom class with appropriate properties (or fields). and use Dictionary as Stefan already said. Key will be your 1st Letter (A,B,C,...)

Example code that Stean proposed as well:

class Foo
{
   public string Text1 {get;set;}
   public string Text2 {get;set;}
}


//inside your method when reading file:

Dictionary<string, List<Foo>> dic = new Dictionary<string, List<Foo>>();
            using (StreamReader sr = new StreamReader(@"FilePath"))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {

                    string[] data = line.Split(',');
                    if (!dic.ContainsKey(data[0]))
                        dic.Add(data[0], null);
                    else
                    {
                        for (int i = 1; i < data.Length; i++)
                            dic[data[0]].Add(new Foo { Text1 = data[1], Text2 = data[2] });
                    }
                }
            }


Mitja


rsbme on Thu, 20 Dec 2012 17:53:59


Thanks for the responses.

Mitja, I tried your code and am getting a "NullReferenceException was unhandled" error at dic[data[0]].Add(new Foo{Text1 = data[1],  Text2 = data[2]});

I cannot figure out why I'm getting it and what I need to do to correct it.  If you can help out that would be great.  Thanks.

Louis.fr on Fri, 21 Dec 2012 07:38:31


for (int i = 1; i < data.Length; i++)
    dic[data[0]].Add(new Foo { Text1 = data[1], Text2 = data[2] });


What's that loop for? You're adding three Foo objects with the same values to the list.

Louis.fr on Fri, 21 Dec 2012 07:41:30


Thanks for the responses.

Mitja, I tried your code and am getting a "NullReferenceException was unhandled" error at dic[data[0]].Add(new Foo{Text1 = data[1],  Text2 = data[2]});

I cannot figure out why I'm getting it and what I need to do to correct it.  If you can help out that would be great.  Thanks.


That's because no List is ever created in the dictionary. Here's a correction of Mitja's code:
class Foo
{
   public string Text1 {get;set;}
   public string Text2 {get;set;}
}
//inside your method when reading file:
Dictionary<string, List<Foo>> dic = new Dictionary<string, List<Foo>>();
using (StreamReader sr = new StreamReader(@"FilePath"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        string[] data = line.Split(',');
        if (!dic.ContainsKey(data[0]))
            dic.Add(data[0], new List<Foo>());
        dic[data[0]].Add(new Foo { Text1 = data[1], Text2 = data[2] });
    }
}

rsbme on Fri, 21 Dec 2012 14:53:52


That did it.  Thanks.