今天我正在开发一个TextToSpeech应用程序,我遇到了一种情况,我需要检查用户选择的语音是否安装在计算机上.
为此,我可以使用foreach:
bool foundVoice = false; foreach (var v in installedVoices) { if (v.VoiceInfo.Name.Contains(selectedVoice) && v.VoiceInfo.Culture.ToString() == selectedCulture) { foundVoice = true; break; } }
或lamda表达式:
var foundVoice = installedVoices.FirstOrDefault(v => v.VoiceInfo.Name.Contains(selectedVoice) && v.VoiceInfo.Culture.ToString() == selectedCulture);
installedVoices是ReadOnlyCollection< InstalledVoice>来自SpeechSynthesizer.
毫无疑问,lambda表达式看起来比foreach更干净,但哪一种更好用?
根据我的测试,foreach似乎比lambda表达式略快.
此外,如果需要对InstalledVoice立即采取行动,将来可以扩展foreach和lambda.