开发者

linq group & sum query

开发者 https://www.devze.com 2023-04-01 06:42 出处:网络
I have an Entity Framework object which represents a telephone call. How can I group the dialed numbers by duration

I have an Entity Framework object which represents a telephone call.

How can I group the dialed numbers by duration and project that into { Number = xxx, DurationSum = yyy }

I'm a linq newbie and can't seem to get 开发者_如何学运维it right.


I think you want something like:

var query = from call in db.Calls
            group call by call.Number into g
            select new { Number = g.Key, DurationSum = g.Sum(c => c.Duration) };


Assume that you have a class like this

class DialedNumber {
    public string Number { get; set; }
    public int Duration { get; set; }
}

And you have a collection named dialedNumbers. You can use a query like this

var groupResult = from dialNumber in dialNumbers
                  group dialNumber by dialNumber.Number
                  into dialNumberGroup
                  select new { 
                               Number = dialNumberGroup.Key, 
                               DurationSum = dialNumberGroup.Sum(d => d.Duration) 
                             };

I haven't tested it yet. I hope this will answer your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消