0

I want to create a function which will return the matrix, but I have a problem with limit the time of put the data to console.

public static List<List<int>> CreateMatrix()
{
    List<List<int>> matrix = new List<List<int>>();
    List<int> row = new List<int>();

    do
    {    
        row = Array.ConvertAll<string, int>(Console.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries), int.Parse).OfType<int>().ToList();
        matrix.Add(row);
    } while (matrix[0].Count == row.Count);

    return matrix;
}

I want to create a loop which will accept the row of numbers, but when nothing is put inside the row at least five seconds for example, then the loop should be break

Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
Dominik
  • 15
  • 3
  • See doc on the property, public static bool KeyAvailable { get; }, on Microsoft's detail documentation site, https://learn.microsoft.com/en-us/dotnet/api/system.console.keyavailable?view=net-7.0 – MZM Dec 05 '22 at 23:11
  • I think you're going to need to add some sort of timeout to the _Console.ReadLine()_ operation, to check for the idle period. Take a look at this post, which talks about this very topic - https://stackoverflow.com/questions/57615/how-to-add-a-timeout-to-console-readline – Nick Scotney Dec 05 '22 at 23:17

1 Answers1

0

Using one of the examples from This Post, I've created a simple example for you which will add items entered on the console to a List collection. Hopefully it will be a good starting point for you to be able to do what you need.

public static void Main()
{
    int waitTimeInSeconds = 10;
    List<string> matrix = new();

    do
    {
        var task = Task.Factory.StartNew(Console.ReadLine);
        var result = Task.WaitAny(new Task[] { task }, TimeSpan.FromSeconds(waitTimeInSeconds)) == 0
            ? task.Result : string.Empty;

        if (!String.IsNullOrEmpty(result))
        {
            matrix.Add(result);
        }
        else
        {
            break;
        }

    } while (true);

    if (matrix is not null)
    {
        Console.WriteLine($"# Items Added to Array: {matrix.Count}\n");

        foreach (var m in matrix)
        {
            Console.Write(m);
        }
    }
}

Reviewing your code however, I'm not sure what you're trying to achieve in your while loop.

Your row variable looks to take the input of the console.ReadLine() and convert it to an integer, but you haven't considered if the input isn't of type integer, as if not, it will cause a System.FormatException.

Secondly, it seems like you're returning a list of list simply because that's the type which Array.ConvertAll().ToList() returns and you want a to return multiple values. I suspect you just want to return the list of values that you've read from the console instead.

Just some food for thought

Nick Scotney
  • 269
  • 1
  • 2
  • 11