IComparable в WPF - PullRequest
       36

IComparable в WPF

0 голосов
/ 30 марта 2020

Мне нужно реализовать кнопку поиска, которая будет сравнивать значение из моего TextBox со значениями в массивах и, если они совпадают, возвращает индекс, в противном случае возвращает -1. Я уже реализовал случайные массивы double и int, а также весь интерфейс и кнопки. Необходимо использовать IComparable и CompareTo(), но я не знаю, как это реализовать. Я пытался реализовать метод Search, но он не работает, я не знаю, как вызвать его в обработчике событий SearchButton_Click.

Это то, что у меня есть:

WPF APP

public partial class MainWindow : Window 
{
    int[] numb = new int[6];
    double[] numb2 = new double[6];

    public MainWindow () 
    {
        InitializeComponent ();
    }

    //Create Int
    private void Button_Click (object sender, RoutedEventArgs e) 
    {
        resultsBox.Items.Clear ();
        resultsBox.Items.Add ("Index Value\n");
        Random rnd = new Random ();
        for (int i = 0; i < 6; i++) {
            numb[i] = rnd.Next (0, 999);
            string m = i.ToString () + "\t" + numb[i].ToString ();
            resultsBox.Items.Add (m);
        }
    }

    //Create Double
    private void CreateDouble_Click (object sender, RoutedEventArgs e) 
    {
        resultsBox.Items.Clear ();
        resultsBox.Items.Add ("Index Value\n");
        Random rnd = new Random ();
        for (int i = 0; i < 6; i++) {
            numb2[i] = Math.Round (rnd.NextDouble () * (999), 2);
            string m = i.ToString () + "\t" + numb2[i].ToString ();
            resultsBox.Items.Add (m);
        }
    }

    //Search
    private void SearchButton_Click (object sender, RoutedEventArgs e) { }

    static int Search<T> (T[] dataArray, T searchKey) where T : IComparable<T> 
    {
        //Iterate through the array.
        for (int iter = 0; iter < dataArray.Length; iter++) {
            //Check if the element is present in the array.
            if (dataArray[iter].CompareTo (searchKey) == 0) {
                //Return the index if the element is present in the array.
                return iter;
            }
        }
        //Otherwise return the index -1.
        return -1;
    }
}

Спасибо!

1 Ответ

0 голосов
/ 31 марта 2020

Сначала вы должны дать TextBox имя, чтобы вы могли ссылаться на него в своем коде, чтобы получить ключ поиска. Затем по нажатию кнопки необходимо проверить тип числового ключа поиска c, чтобы определить целевой массив поиска. Затем передайте оба аргумента методу Search():

MainWindow.xaml

<Window>
  ...

  <TextBox x:Name="SearchInputBox` />
  ...
</Window>

MainWindow.xaml.cs

public partial class MainWindow : Window 
{
  private readonly int arraySize = 6;
  private int[] IntegerValues { get; }
  private double[] DoubleValues { get; }

  public MainWindow() 
  {
    InitializeComponent();
    this.IntegerValues = new int[arraySize];
    this.DoubleValues = new double[arraySize];
  }

  // Create Int
  private void Button_Click(object sender, RoutedEventArgs e) 
  {
    resultsBox.Items.Clear();
    resultsBox.Items.Add("Index Value\n");

    Random rnd = new Random();
    for (int index = 0; index < arraySize; index++) 
    {
      this.IntegerValues[index] = rnd.Next(0, 999);
      string item = index.ToString() + "\t" + this.IntegerValues[index].ToString();
      resultsBox.Items.Add(item);
    }
  }

  // Create Double
  private void CreateDouble_Click(object sender, RoutedEventArgs e) 
  {
    resultsBox.Items.Clear();
    resultsBox.Items.Add("Index Value\n");

    Random rnd = new Random();
    for (int index = 0; index < arraySize; index++) 
    {
      this.DoubleValues[index] = Math.Round(rnd.NextDouble() * 999, 2);
      string item = index.ToString() + "\t" + this.DoubleValues[index].ToString();
      resultsBox.Items.Add(item);
    }
  }

  // Handle search button clicked
  private void SearchButton_Click(object sender, RoutedEventArgs e) 
  {
    string numericString = this.SearchInputBox.Text;

    int resultIndex = -1;
    if (int.TryParse(numericString, out int integerSearchPredicate)
    {
      resultIndex = MainWindow.Search(this.IntegerValues, integerSearchPredicate);
    }
    else if (double.TryParse(numericString, out int doubleSearchPredicate)
    {
      resultIndex = MainWindow.Search(this.DoubleValues, doubleSearchPredicate);
    }
  }

  static int Search<T>(T[] dataArray, T searchKey) where T : IComparable<T> 
  {
    // Iterate over the array.
    for (int index = 0; index < dataArray.Length; index++) 
    {
      // Check if the element is present in the array.
      if (dataArray[index].CompareTo(searchKey) == 0) 
      {
        //Return the index if the element is present in the array.
        return index;
      }
    }

    // Otherwise return the index -1.
    return -1;
  }
}
...