简体   繁体   English

c#linq分组依据-访问其他属性,选择新的

[英]c# linq group by - Access other properties inside select new

I'm converting a grouped Type1 list in another Type2 list and I'm wondering how it is possible to define a property of Type2 object as a concatenation of other and just defined Type2 properties, inside select new from grouped items. 我正在将一个分组的Type1列表转换为另一个Type2列表,并且我想知道如何在从分组项中选择new的同时,将Type2对象的属性定义为其他和刚刚定义的Type2属性的串联。

My code is the following: 我的代码如下:

List<Type1> list1 = GetList1();

List<Type2> list2 = (from r in list1
                    group r by new
                    {
                         r.Prop1,
                         r.Prop2,
                         r.Prop3
                    }
                    into groupedRequest
                     select new Type2()
                     {
                         Prop1 = groupedRequest.Key.Prop1,
                         Prop2 = GetProp2FromComplexOperation(groupedRequest.Key.Prop1),
                         Prop3 = Prop1 + Prop2 //<---- The name Prop1 does not exists in the current context
                     }).ToList<Type2>();

I'm not able to access to Prop1 and Prop2 inside new Type2() creation. 我无法在创建的Type2()中访问Prop1和Prop2。 Is it possible to do that in any manner? 有可能以任何方式做到这一点吗?

I know is possible to calculate 我知道可以计算

Prop3 = groupedRequest.Key.Prop1 + GetProp2FromComplexOperation(groupedRequest.Key.Prop1);

but I want avoid to call again GetProp2FromComplexOperation. 但我想避免再次调用GetProp2FromComplexOperation。

Thanks in advance! 提前致谢!

You can use let like this: 您可以这样使用let

List<Type2> list2 = (from r in list1
                    group r by new
                    {
                         r.Prop1,
                         r.Prop2,
                         r.Prop3
                    }
                    into groupedRequest
                    let p1 = groupedRequest.Key.Prop1
                    let p2 = GetProp2FromComplexOperation(groupedRequest.Key.Prop1)
                     select new Type2()
                     {
                         Prop1 = p1,
                         Prop2 = p2,
                         Prop3 = p1 + p2
                     }).ToList<Type2>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM