0

I have this user input:

first line: 1 2 second line: 0 1 1 third line: 1 0 0

with the code below I have managed to read all lines and store them into a list, in the last bit of code what I want to do is to store the values like integer types Int32, can anyone tell me of a better way to do this operation?

 List<string> lines = new List<string>();
 string line;
 int count = -2;
 int totCount = 0;
 while (count<=totCount)
       {
          line = Console.ReadLine();

          lines.Add(line);
          count++;               
       }


 var line1 = lines[0];
 var line2 = lines[1];
 var line3 = lines[2];

 string[] ee = line1.Split(new char[] { ' ' }, StringSplitOptions.None);
 int c = Int32.Parse(ee[1]);
 ...
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Ako
  • 93
  • 2
  • 13
  • 1
    what is your expected output? we cannot recommend a useful data structure unless we know what you intend to achieve. you could store them in an array, in a `List`, ... if `trainInfo` is line1+line2+line3, you should show that because the current code does not compile. – Cee McSharpface Sep 15 '18 at 16:47
  • https://stackoverflow.com/questions/1297231/convert-string-to-int-in-one-line-of-code-using-linq/37033140#37033140 – Slai Sep 15 '18 at 16:55
  • my bad, it should say line1 and not traininfo, sry! the output is the digits that are entered by the user to be stored into integer types – Ako Sep 15 '18 at 17:19
  • and would you expect one item per line, with the integers of that line inside (as in @Dmitry's answer), or just a contiguous list of numbers? – Cee McSharpface Sep 15 '18 at 17:21

2 Answers2

4

If I've understood you right and you want to input a collection List<int[]>, let's extract a method:

 private static IEnumerable<int[]> ReadData() {
   while (true) {
     Console.WriteLine("Next line of integers or q for quit");
     string input = Console.ReadLine().Trim();

     if (input == "q")
       break;

     yield return input
       .Split(new char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries)
       .Select(item => int.Parse(item)) // int.TryParse will be better
       .ToArray();
   }
 }

Then you can put

 List<int[]> trainInfo = ReadData().ToList();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
-1
public struct Data
{
    public Data(int intValue)
    {
        IntData = intValue;
    }

    public int IntData { get; private set; }  
}

var list = new List<Data>();
list.Add(new Data(123));
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
Saleem Kalro
  • 1,046
  • 9
  • 12