0

I have a problem with my code, I am supposed to import a list from a .txt file, each line in the txt file has two item, name and city for example

Alex###London
Justin###Texas

I have a code that imports this list from the txt file into the listBox1 but I can not split Alex and London. My class is User and I want to add Alex to name and London to City. this is the code I use but it doesnt work

List<User> userList = new List<User>(); 
      
            var charArray = listBox1.Text.Split('#' + "#" + "#");
            string Name = charArray[0];
            string City = charArray[1];
            User user = new User(Name, City);
            userList.Add(user);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Ali Nouri
  • 11
  • 1

2 Answers2

0

You can Split by a string with multiple chars, for example with this overload:

string[] nameAndCity = listBox1.Text.Split(new[]{"###", StringSplitOptions.None});
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

its very strange way to store your data this, if u write it by yourself dont do this, better store data in JSON or XMS, rewrite it if u can, with your data structure u can do this

            var yourData = "Alex###London  Justin###Texas\nJustin1###Texas1 Justin2###Texas2";
            var separators = new string[] { "\n", " " };
            var stringUsers = yourData.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            foreach(var stringUser in stringUsers)
            {
                var userData = stringUser.Split("###");
                string Name = userData[0];
                string City = userData[1];
                Guldkort user = new Guldkort(Name, City);
                userList.Add(user);
            }

check if i understood your data structure right and if your input data is correct

  • Hi, thank you so much for helping, I know this is not correct way to add items in my list but my teacher asked me to do it. I have one problem with your code, in yourData = here I cant write anything because my list is supposed to read txt files and the list is very long, my teacher has already created the list in a txt file and my code is supposed to read the txt file and save the list from txt file – Ali Nouri Nov 03 '22 at 23:03