Сравнение ингредиентов различных списков перечислений - PullRequest
0 голосов
/ 08 декабря 2018

Я пытаюсь сравнить компоненты двух списков Enum одним нажатием кнопки, и я хочу получать разные сообщения в зависимости от совпадения.

Точнее: у меня под рукой разные рецепты, и если мои выбранные ингредиенты совпадают с одним из них, я получу специальное сообщение.Если мои ингредиенты не совпадают ни с чем, я получу стандартное сообщение.

Вот что я пытался, но не работал должным образом:

public void DrinkButton_Click(object sender, RoutedEventArgs e)
{
    foreach (var recipe in RecipeList)
    {
        List<Ingredients> copy = new List<Ingredients>(selectedPotion.MyIngredients);

        if (copy.Count == recipe.Recipe.Count)
        {
            for (int i = copy.Count - 1; i >= 0; i--)
            {
                Ingredients item = selectedPotion.MyIngredients[i];

                if (recipe.Recipe.Contains(item))
                {
                    copy.Remove(item);
                }
                if (copy.Count == 0)
                {
                    recipe.DrinkEffect();
                }
            }
        }
        else
        {
            MessageBox.Show("Doesn't taste like anything!", "Announcement!", MessageBoxButton.OK, MessageBoxImage.Information);
        }
    }
}

Ответы [ 3 ]

0 голосов
/ 08 декабря 2018

Исходя из ответов, мое окончательное решение: (Я все еще получал "System.NullReferenceException: 'Ссылка на объект не установлена ​​на экземпляр объекта." Ошибка.)

    public void DrinkButton_Click(object sender, RoutedEventArgs e)
    {            
        foreach (var recipe in RecipeList)
        {               
            bool equalIngredients = recipe.Recipe.All(selectedPotion.MyIngredients.Contains) && recipe.Recipe.Count == selectedPotion.MyIngredients.Count;

            if (equalIngredients)
            {
                recipe.DrinkEffect();
                goto NextStep;
            }
        }
        MessageBox.Show("Doesn't taste like anything!", "Announcement!", MessageBoxButton.OK, MessageBoxImage.Information);
        NextStep: return;      
    }  
0 голосов
/ 08 декабря 2018

Вот самое последнее:

    public void DrinkButton_Click(object sender, RoutedEventArgs e)
    {
        if (selectedPotion == null)
        {
            MessageBox.Show("Please select a potion to drink", "Help Window", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }
        else
        {
            foreach (var recipe in RecipeList)
            {
                bool equalIngredients = recipe.Recipe.All(selectedPotion.MyIngredients.Contains) && recipe.Recipe.Count == selectedPotion.MyIngredients.Count;

                if (equalIngredients)
                {
                    recipe.DrinkEffect();
                    goto NextStep;
                }
            }
            MessageBox.Show("Doesn't taste like anything!", "Announcement!", MessageBoxButton.OK, MessageBoxImage.Information);
        NextStep: return;
        }
    }
0 голосов
/ 08 декабря 2018

Вы можете использовать Linq's All, чтобы проверить, содержат ли оба Списка ингредиентов одинаковые элементы:

public void DrinkButton_Click(object sender, RoutedEventArgs e)
{
    if (selectedPotion == null)
    {
        MessageBox.Show("Please select a potion to drink", "Help Window", MessageBoxButton.OK, MessageBoxImage.Information);
        return;
    }

    foreach (var recipe in RecipeList)
    {
        bool equalIngredients = recipe.Recipe.All(selectedPotion.MyIngredients.Contains) &&
                                    recipe.Recipe.Count == selectedPotion.MyIngredients.Count;

        if (equalIngredients)
        {
            recipe.DrinkEffect();
            return;
        }
    }

    MessageBox.Show("Doesn't taste like anything!", "Announcement!",
                        MessageBoxButton.OK, MessageBoxImage.Information);
}

Это зациклит все элементы в RecipeList и проверит, равняется ли Recipe элемента selectedPotion.MyIngredients.Если это так, он вызовет метод DrinkEffect() для текущего элемента, в противном случае он отображает «Не имеет вкуса!» - MessageBox.

Несколько замечаний:

  • recipe.Recipe выглядит просто неправильно, возможно, стоит использовать более точное наименование
  • Код в настоящее время не проверяет, является ли selectedPotion null или нет, я вижу потенциал для исключения NullReferenceException
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...