2012-02-09 116 views
1

如何獲得特定組中元素的數量?因此,在下面的查詢中,我想知道每個帳戶有多少個已取消和有效的訂閱。我得到的是0或1,取決於他們是否至少有一個取消或活動訂閱。如何計算每個組中的元素數量?

from a in Accounts 
let subs = (
     from s in Subscriptions.Where(s=>s.AccountId == a.Id) 
     group s by s.Status into bystatus 
     select bystatus 
    ) 
let csubs = subs.Count (s =>s.Key == "Cancelled") 
let asubs = subs.Count (s => s.Key == "Active") 
orderby a.Name 
select new { a.Name,a.AccountNumber, a.Status, ActiveSubscriptionCount = asubs, CancelledSubscriptionCount = csubs } 

回答

0

它看起來像你彙總數據每個帳戶。這是你的意圖嗎?如果要在所有帳戶的累計資料,您可以做要麼...

var data = // your above code
int activeSubs = data.Sum(x => x.ActiveSubscriptionCount);
int cancelledSubs = data.Sum(x => x.CancelledSubscriptionCount);

......或者......

var data = Subscriptions.GroupBy(s => s.Status);
var activeSubs = data.Count(s => s.Key == "Active");
var cancelledSubs = data.Count(s => s.Key == "Cancelled");

+0

我希望它每個帳戶彙總。 – 2012-02-10 19:44:33

相關問題