The following lines are added to the List<string> : 1|Александр|Иванов

How each text through the separator | write to a separate variable? This miracle must be implemented in a loop, because there are many such lines.

Or tell me, please, what can I replace? I think the description is clear what I need.

Or maybe you can even directly implement what I need? In short, give an example with the line above. 1 is a unique number ( ID ), I need to get a first and last name by ID .

  • 3
    I will express support for the answers that offer to introduce a class of type Person (and, possibly, a Dictionary for a quick search). However, I suggest going further and removing List<string> altogether. There must be a collection of instances of Person . And for storing in a file (that's probably where your lines come from) this collection should be serialized into JSON or XML. - Alexander Petrov

3 answers 3

stringsArray - store strings here

 for (int x=0; x<stringsArray.Length; x++) { string[] result = stringsArray[x].Split('|'); // куда вы строки складывать будете я без понятия // в данном случае на каждом проходе цикла будете иметь разбитую строку } 
  • one
    Thank you all very much for the answers, this option came up perfectly for me, BUT from the options above, I also learned something. Thank! - Maxim
 public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } List<string> list = new List<string>() { "1|Александр|Иванов", "2|Александра|Иванова" }; var q = from s in list let parts = s.Split('|') select new Person { Id = Convert.ToInt32(parts[0]), FirstName = parts[1], LastName = parts[2] }; foreach (var i in q) { System.Console.WriteLine($"Id = {i.Id}"); } 

I need to get a first and last name by ID.

 var result = q.FirstOrDefault(x => x.Id == 1); Console.WriteLine($"Имя = {result.FirstName}, Фамилия = {result.LastName}"); 
     public class Person { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public Dictionary<int, Person> ParsePeople(List<string> aLines, List<string> anErrors) { anErrors.Clear(); Dictionary<int, Person> result = new Dictionary<int, Person>(); int id; string[] delimiters = new string[] { "|" }; foreach (string line in aLines) { string[] parts = line.Split(delimiters); if (parts.Length == 3 && int.TryParse(parts[0], out id)) { result[id] = new Persion() { ID = id, FirstName = parts[1], LastName = parts[2]}; } else { anErrors.Add(line); } } return result; }