这可能是一个基本的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