Ali Nouri
Ali Nouri

Reputation: 11

splitting one item in listBox into two Items

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);

Upvotes: 0

Views: 129

Answers (2)

David Gasuk
David Gasuk

Reputation: 3

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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460158

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

string[] nameAndCity = listBox1.Text.Split(new[]{"###", StringSplitOptions.None});

Upvotes: 0

Related Questions