[英]Comparing the ingredients of various lists of enums
我試圖在單擊按鈕時比較兩個枚舉列表的成分,但我想根據匹配結果接收不同的消息。
更准確地說:我手頭有不同的食譜,如果我選擇的食材與其中一種相匹配,我會收到一條特別的消息。 如果我的食材與任何東西都不匹配,我將收到一條標准消息。
這是我嘗試過但無法正常工作的內容:
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);
}
}
}
您可以使用Linq的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 根據答案,他得出了我的最終解決方案:(我仍然收到“ 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;
}
這是最新的:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.