這可能是一個基本的LINQ問題。我需要選擇一個對象,如果它是空的選擇另一個。我使用LINQ to對象以下列方式,我知道可以做到更快,更好,更清潔......如何將這些相似的linq查詢合併爲一個?
public Attrib DetermineAttribution(Data data)
{
var one = from c in data.actions
where c.actionType == Action.ActionTypeOne
select new Attrib
{
id = c.id,
name = c.name
};
if(one.Count() > 0)
return one.First();
var two = from c in data.actions
where c.actionType == Action.ActionTypeTwo
select new Attrib
{
id = c.id,
name = c.name
};
if (two.Count() > 0)
return two.First();
}
兩個LINQ操作上區別僅在where子句,我知道有一種方法將它們結合起來。任何想法將不勝感激。
您應該使用.Any()而不是.Count()。 Count()遍歷整個序列,而Any只檢查第一個項目是否存在。 – Rubys 2010-05-04 15:52:36
@MikeD:應該指出的是,上面的代碼不能編譯,因爲在兩個序列沒有你正在尋找的項目的情況下,你不會返回一個值。 – casperOne 2010-05-04 15:59:53
對不起,我試圖把我的方法清理成SO窗口中的簡明內容,顯然太多了。 – MikeD 2010-05-04 16:54:41