日期:2014-05-20  浏览次数:21052 次

如何用LINQ只查询一条记录?
下面这段代码的目的为查询满足条件的记录,并返回它。
如果有多条满足,只返回第一条;如果没有满足条件的记录,则返新创建的一个MSG_DESC对象。
现在的问题是当执行msgDesc.Count()时,就需要查询出所有的结果。这样势必会造成效率低下,因为我只需要第一条记录就可以了。
请问该如何做?

C# code
            var msgDesc = from item in _MsgList
                          where item.MD_TABLE.Equals("tableset") && item.MD_FIELD.Equals("ID") && item.MD_VALUE.Equals(_id.ToString())
                          select item;
            if (msgDesc.Count() == 0)
                return new MSG_DESC();
            else
                return msgDesc.First();


------解决方案--------------------
C# code

var first=_MsgList.FirstOrDefault(item=>item.MD_TABLE.Equals("tableset") && item.MD_FIELD.Equals("ID") && item.MD_VALUE.Equals(_id.ToString())

------解决方案--------------------
FirstOrDefault,如果返回null则说明没有数据。
------解决方案--------------------
var msgDesc =( from item in _MsgList
where item.MD_TABLE.Equals("tableset") && item.MD_FIELD.Equals("ID") && item.MD_VALUE.Equals(_id.ToString())
select item).FirstOrDefault();

return msgDesc ==null? new MSG_DESC():msgDesc ;

------解决方案--------------------
(语句).FirstOrDefault();就可以了
------解决方案--------------------
Only one line of code.
C# code

return MsgList.FirstOrDefault(x=>
              x.MD_TABLE.Equals("tableset") && 
              x.MD_FIELD.Equals("ID") && 
              x.MD_VALUE.Equals(_id.ToString()))??new MSG_DESC();

------解决方案--------------------
public Entity.产品套餐配置表 SeleteOnePackagePrice(int colorid,int mealid) {
var context = new Entity.Entities();
string price = string.Empty;
Entity.产品套餐配置表 mm = new Entity.产品套餐配置表();
try
{
var queryTab = from custom in context.表名 where (custom.COLOUR_ID == colorid && custom.P_ID == mealid) select custom;
if (queryTab.Count() > 0) {
mm = queryTab.FirstOrDefault();
}
}
catch
{
}

return mm;
}
建议不要用First,用FirstOrDefault,为什么呢?你可以上网查下资料