我想使用linq提取特定元素。如果這個元素不在給定的列表中,我想使用該列表中的任何其他元素。使用Linq選擇特定元素
有沒有更簡單的方法來實現這個?這裏是我目前的解決方案:
string content = String.Empty;
Text t = texts.FirstOrDefault(x => x.Display == Display.Terminal);
if (t != null)
{
content = t.Value;
}
else
{
t = texts.FirstOrDefault();
if (t != null)
content = t.Value;
}
謝謝。
編輯:使用阿薩德建議的解決方案,我改變了代碼
string content = (texts.FirstOrDefault(x => x.Display == Display.Terminal) ?? texts.FirstOrDefault() ?? new Text()).Value;
謝謝!我不知道''''操作符。所以我修改了我的問題的解決方案。 'string content =(texts.FirstOrDefault(x => x.Sink == DisplaySink.Terminal)?? texts.FirstOrDefault()?? new Text())。Value;' – user3399383