请教下各位linq高手~
public int GetFrientDyCOntentMaxId(int userid){
var list = (from a in DataContext.relation
join c in DataContext.T_users
on a.uid equals c.userid
join dy in DataContext.DyContent
on a.uid equals dy.userid
where a.userid == userid && a.type == 1012 && a.flag == false && dy.dyMark == 0 && dy.type!=140008 && dy.type!=140009 && dy.type!=40009 && dy.type!=40007 && dy.type!=40005 && dy.type!=40011 && dy.type!=40012 && dy.type!=140010
select new { dy.id }).ToList();
int id = 0;
if (list.Count() != 0)
{
id = list.Max(o => o.id);
}
return id;
}
请问下这个方法还能怎么优化吗? --------------------编程问答-------------------- public int GetFrientDyCOntentMaxId(int userid)
{
var id= (from a in DataContext.relation
join dy in DataContext.DyContent
on a.uid equals dy.userid
where a.userid == userid
&& a.type == 1012
&& a.flag == false
&& dy.dyMark == 0
&& dy.type!=140008
&& dy.type!=140009
&& dy.type!=40009
&& dy.type!=40007
&& dy.type!=40005
&& dy.type!=40011
&& dy.type!=40012
&& dy.type!=140010
select new { dy.id }).Max(p=>p.id);
return id;
}
DataContext.T_users 实际没有用到,可以删除。
--------------------编程问答-------------------- 象dy.type!=140008 。。。。
这种硬代码一般不提倡,个人觉得可以把那些值放到一个数组里面,作为参数传进来,这样,万一以后要增加几个,也方便。
var typeArr = {140008 ,140009 ,140010 ,40009 ,40007 ,40005 ,40011 ,40012 };
然后用containsa()比较。
public int GetFrientDyCOntentMaxId(int userid,typeArr )
{
var id= (from a in DataContext.relation
join dy in DataContext.DyContent
on a.uid equals dy.userid
where a.userid == userid
&& a.type == 1012
&& a.flag == false
&& dy.dyMark == 0
&& ! typeArr.contains(dy.type)
select new { dy.id }).Max(p=>p.id);
return id;
}
--------------------编程问答-------------------- 直接写SQL, --------------------编程问答-------------------- 如果是 linq to entities, Contains 不能用
Contains 翻译过来后其实还是一串 Or ,效率上其实并 IN 要差,如果你真的对 performance 非常在意,你可以直接用ESQL 。或者,你直接用 selectMany,把你的 condition 写到 predicate 里面
补充:.NET技术 , LINQ