c# – 无效的匿名类型成员声明

我有一个问题,下面的代码,应该工作,根据this MSDN Forums post

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace LINQTest
{
    class Program
    {
        class Schedule
        {
            public int empid { get; set; }
            public int hours { get; set; }
            public DateTime date { get; set; }
            public DateTime weekending { get; set; }
        }

        static void Main(string[] args)
        {
            List<Schedule> Schedules = new List<Schedule>();

            var bla = from s in Schedules
                      group s by new { s.empid, s.weekending} into g
                      select new { g.Key.empid, g.Key.weekending, g.Sum(s=>s.hours)};
        }
    }
}

我得到的和函数的错误:
无效的匿名类型成员声明。匿名类型成员必须用成员赋值,简单名称或成员访问来声明。

怎么了?

您必须命名用于存储Sum方法结果的属性:

select new { g.Key.empid, g.Key.weekending, Sum = g.Sum(s=>s.hours)};

在从表达式分配值时,编译器无法推断属性名称:

Anonymous Types (C# Programming Guide)

You must provide a name for a property that is being initialized with an expression (…)

http://stackoverflow.com/questions/18856885/invalid-anonymous-type-member-declarator

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – 无效的匿名类型成员声明