English 中文(简体)
如何进入动态类型的领域?
原标题:How to access to a field of a dynamic type?

我试图用 LINQ 检索的 < code> 动力 对象列表中名为 < code_ heryResultViewModel 的类来包抄查询结果。 这些查询包含一个叫做 < code> Worked 的整数字段。 我不应该使用非动态类型, 因为它有其它字段。 我尝试过 :

    var query = new HoursQuery( .. parameters .. );
    this.Result = new ObservableCollection<QueryResultViewModel>(
      query.Execute().Select( x => new QueryResultViewModel( x.Worked )));

但我得到了 " 对象不包含对工作的定义 ",我不知道能否在不改变查询返回类型的情况下固定它。

执行代码也可能有用 :

    var res = some_list.GroupBy(a => new { a.Employee, a.RelatedTask, a.Start.Month })
       .Select(g => new { K = g.Key, Worked = g.Sum(s => s.Duration.TotalHours) });

强势EDIT :效果很好,但也许不太优雅。

    public class HQueryDTO
    {
        public double Worked;
        public object K;
    }

    public IEnumerable<dynamic> Execute()
    {
        var list = base.Execute();
        return res = list.GroupBy(a => new { a.Employee, a.RelatedTask } )
          .Select(g => new HQueryDTO { K = g.Key, Worked = g.Sum(s => s.Duration.TotalHours) });
    }

当结果有类型时, 可以返回动态 。

最佳回答

I m 假设 您在编译时收到错误,在此情况下,只需通过投影引入 动态 :

.Select(x => new QueryResultViewModel( ((dynamic)x).Worked ))
问题回答

我假设 Execute 的签名类似于 object effecte () <(/code)>。 如果您返回 动力 , 它应该有效 。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...