开发者

many to one linq projection

开发者 https://www.devze.com 2023-03-30 23:13 出处:网络
How can I write this in one query? var query开发者_运维问答 = this.ObjectContext.SomeCollection.

How can I write this in one query?

var query开发者_运维问答 = this.ObjectContext.SomeCollection.
                .Where(...)
                .Select(f => new {somenumber = f.somenumber});

MyType type = new MyType()
                 {
                    Sum = query.Sum(f => f.somenumber)
                 }


Your use of the anonymous type is completely unnecessary since you have only one property in the projection. You can simply take the query and enclose it inside the object initializer for MyType. Note that this is fine as long as you're not reusing the projection elsewhere (in which case you would pull it outside and then reuse it).

var type = new MyType {
               Sum = this.ObjectContext
                         .SomeCollection
                         .Where(SomeCondition)
                         .Select(f => f.somenumber)
                         .Sum()
           };

Additionally, you could reduce .Select(f => f.somenumber).Sum() to Sum(f => f.somenumber).


MyType type = new MyType {
                Sum =
                 this.ObjectContext.SomeCollection
                 .Where(...)
                 .Select(f => f.somenumber)
                 .Sum() };

or even

MyType type = new MyType {
                Sum =
                 this.ObjectContext.SomeCollection
                 .Where(...)
                 .Sum(f => f.somenumber) };

shoud do the trick

0

精彩评论

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