Code funktioniert nicht?

2 Antworten

Das Ermitteln der Indizes ist in Ordnung. Bei deiner Eingabe wirst du die erwarteten Zahlen 1, 2, 4, 5, 6 und 3 erhalten. Das kannst du im Übrigen selbst leicht prüfen, indem du dir entweder Konsolenausgaben einbaust oder via Breakpoint im Debugging-Modus in indices schaust.

Ich würde dir allerdings empfehlen, diese Methode aufzutrennen. Die Methode selbst filtert die ausgewählten Listen aus und eine Helfermethode übernimmt die Ermittlung der einzelnen Indizes.

Schau nach, wie viele Einträge in fileList zur Programmlaufzeit stehen. Bei weniger als vier Einträgen würdest du das Ergebnis erhalten, welches du selbst beschreibst.

klappt das ?:

private List<string> SelectFiles(List<string> fileList)

{

 // Log a message to the user asking for input

 _logger.Log("Bitte geben Sie die Nummern der Handbücher ein, die Sie verarbeiten möchten (kommagetrennt, z.B. 1, 3-5), oder drücken Sie Enter, um alle zu verarbeiten:");

 // Read user input from the console

 string input = Console.ReadLine();

 // Initialize the list of selected files

 List<string> selectedFiles = new List<string>();

 // If no input is provided, process all files

 if (string.IsNullOrEmpty(input))

 {

  selectedFiles = new List<string>(fileList);

 }

 else

 {

  // Process the input to extract selected file indices

  string[] inputParts = input.Split(',');

  // Use a HashSet to avoid duplicate indices

  HashSet<int> indices = new HashSet<int>();

  foreach (string part in inputParts)

  {

   if (part.Contains('-'))

   {

    // Split the range and parse the start and end values

    string[] rangeParts = part.Split('-');

    if (rangeParts.Length == 2 &&

      int.TryParse(rangeParts[0].Trim(), out int start) &&

      int.TryParse(rangeParts[1].Trim(), out int end))

    {

     // Add all indices within the specified range to the HashSet

     for (int i = start; i <= end; i++)

     {

      indices.Add(i);

     }

    }

   }

   else if (int.TryParse(part.Trim(), out int index))

   {

    // Add the individual index to the HashSet

    indices.Add(index);

   }

  }

  // Add the selected files based on the collected indices

  foreach (int index in indices)

  {

   // Check if the index is within the valid range

   if (index > 0 && index <= fileList.Count)

   {

    selectedFiles.Add(fileList[index - 1]); // Adjust for 0-based indexing

   }

   else

   {

    // Handle out-of-bound indices, if necessary

    _logger.Log($"Index {index} is out of bounds.");

   }

  }

 }

 return selectedFiles;

}

https://chatgpt.com/share/6d9ceedc-034c-4168-8e4e-38562a891d94