【问题标题】:c# linq group by - Access other properties inside select newc# linq group by - 访问select new里面的其他属性
【发布时间】:2015-01-26 11:56:47
【问题描述】:

我在另一个 Type2 列表中转换一个分组的 Type1 列表,我想知道如何将 Type2 对象的属性定义为其他和刚刚定义的 Type2 属性的串联,在 select new from grouped items 中。

我的代码如下:

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>();

我无法在 new Type2() 创建中访问 Prop1 和 Prop2。 有没有可能以任何方式做到这一点?

我知道可以计算

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

但我想避免再次调用 GetProp2FromComplexOperation。

提前致谢!

【问题讨论】:

    标签: c# linq group-by


    【解决方案1】:

    你可以像这样使用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>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多