Try this:
(尝试这个:)
public static void ShowSound(string userInput2, string[] localPets4, string[] localSounds2)
{
var result =
localPets4
.Zip(localSounds2, (pet, sound) => new { pet, sound })
.Where(x => x.pet == userInput2)
.FirstOrDefault();
if (result != null)
{
Console.WriteLine($"{result.pet} makes the sound {result.sound}");
Console.WriteLine();
}
else
{
Console.WriteLine($"Sorry, {userInput2} isn't in our list of animals");
}
}
The line localPets4.Zip(localSounds2, (pet, sound) => new { pet, sound })
is matching element for element in the localPets4
and localSounds2
arrays and creates a single enumerable in the form of new { pet, sound }
.
(行localPets4.Zip(localSounds2, (pet, sound) => new { pet, sound })
与localPets4
和localSounds2
数组中的element元素匹配,并以new { pet, sound }
的形式创建一个可枚举的元素。)
The .Where(x => x.pet == userInput2)
only retains the elements where pet
equals the userInput2
.
(.Where(x => x.pet == userInput2)
仅保留pet
等于userInput2
的元素。)
This should mean that if there's a match then there's only one match and if there isn't a match then the enumerable is empty.
(这意味着如果有匹配项,那么只有一个匹配项;如果没有匹配项,则可枚举为空。)
Calling .FirstOrDefault()
then either you have the single new { pet, sound }
that manages the input or you have null
. (调用.FirstOrDefault()
然后您将拥有一个管理输入的new { pet, sound }
或拥有null
。)
The rest of the code simply produces the output based on the result
.
(其余代码只是根据result
生成输出。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…