C# Linq to SQL .Sum() without group ... into

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/641682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:26:55  来源:igfitidea点击:

Linq to SQL .Sum() without group ... into

c#linq-to-sql.net-3.5

提问by roman m

I have something like this:

我有这样的事情:

var itemsInCart = from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}

is there any way to do a

有没有办法做一个

itemsCart.Sum() //not sure what to pass into the function

to get the sum of o.WishListItem.Price or do i have to get another iQueryable< T> from the database with group ... into?

获得 o.WishListItem.Price 的总和还是我必须从数据库中获取另一个 iQueryable< T> 与组...进入?

采纳答案by CMS

What about:

关于什么:

itemsInCart.AsEnumerable().Sum(o=>o.Price);

AsEnumerablemakes the difference, this query will execute locally (Linq To Objects).

AsEnumerable有所不同,此查询将在本地执行(Linq To Objects)。

回答by eglasius

you can:

你可以:

itemsCart.Select(c=>c.Price).Sum();

itemsCart.Select(c=>c.Price).Sum();

To hit the db only once do:

只击中数据库一次,请执行以下操作:

var itemsInCart = (from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
                  ).ToList();
var sum = itemsCart.Select(c=>c.Price).Sum();

The extra round-trip saved is worth it :)

节省的额外往返是值得的:)

回答by Jonathan Parker

Try:

尝试:

itemsCard.ToList().Select(c=>c.Price).Sum();

Actually this would perform better:

实际上这会表现得更好:

var itemsInCart = from o in db.OrderLineItems
              where o.OrderId == currentOrder.OrderId
              select new { o.WishListItem.Price };
var sum = itemsCard.ToList().Select(c=>c.Price).Sum();

Because you'll only be retrieving one column from the database.

因为您只会从数据库中检索一列。

回答by Dirceu

Try this:

尝试这个:

var itemsInCart = from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select o.WishListItem.Price;

return Convert.ToDecimal(itemsInCart.Sum());

I think it's more simple!

我觉得更简单!

回答by Trisped

I know this is an old question but why can't you do it like:

我知道这是一个老问题,但你为什么不能这样做:

db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);

I am not sure how to do this using query expressions.

我不确定如何使用查询表达式来做到这一点。