0

I have a LINQ query like so:

var Item = (from s in contextD.Items where s.Id == Id select s).ToList();

Further down the Item object properties are set like so:

Item.FirstOrDefault().Qty = qtyToUpdate;
Item.FirstOrDefault().TotalPrice = UItem.FirstOrDefault().Qty *  UItem.FirstOrDefault().Price;
 ...

My question is, will calling FirstOrDefault always loop through the result set returned by the query?

Shouldn't a single call be made and put in an object like so:

MyObject objMyObject = new MyObject;
objMyObject = Item.FirstOrDefault();

and then go about setting objMyObject properties.

The first part using FirstOrDefault is actually in the production, I am trying to find out if that's the right way.

Regards.

4

1 回答 1

4

调用 FirstOrDefault 是否总是会遍历查询返回的结果集?

FirstOrDefault()从不循环遍历所有结果集 - 它要么返回第一项,要么返回默认值(如果 set 为空)。同样在这种特殊情况下,甚至不会创建枚举器 - 因此您正在调用类型FirstOrDefault()变量List<T>,只需返回索引处的项目0(如果列表不为空)。如果您要调查Enumerable.FirstOrDefault()实施:

IList<TSource> list = source as IList<TSource>;
if (list != null)
{
    if (list.Count > 0)
    {
        return list[0];
    }
}

但是每次调用时都会调用它FirstOrDefault()

此外,您还缺少“默认”案例。如果您像第一个示例中那样链接方法,则可以获取NullReferenceExceptionlist 是否为空。因此,请确保查询返回了某些内容:

var item = Item.FirstOrDefault();
if (item == null)
    return; // or throw

item.Qty = qtyToUpdate;
var uitem = UItem.FirstOrDefault();
if (uitem == null)
    return; // or throw

item.TotalPrice = uitem.Qty * uitem.Price;

还有一点需要注意 - 如果您FirstOrDefault()在内存收集上执行,则性能几乎没有差异。但是,如果您在不将查询结果保存到列表中的情况下执行它,差异将是巨大的。在这种情况下,每次 FirstOrDefault()调用都会导致新的数据库查询

于 2013-09-19T10:30:28.087 回答