C# 匿名类型成员声明符无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18856885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invalid anonymous type member declarator
提问by chhenning
I have a problem with the following code which should work, according to this MSDN Forums post.
根据这篇 MSDN 论坛帖子,我对以下应该工作的代码有问题。
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)};
}
}
}
I'm getting the error with the sum function: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
我收到 sum 函数的错误:无效的匿名类型成员声明符。匿名类型成员必须使用成员赋值、简单名称或成员访问进行声明。
What's wrong?
怎么了?
采纳答案by MarcinJuraszek
You have to name the property used to store Sum
method result:
您必须命名用于存储Sum
方法结果的属性:
select new { g.Key.empid, g.Key.weekending, Sum = g.Sum(s=>s.hours)};
Compiler can't infer the property name when you're assigning the value from expression:
当您从表达式分配值时,编译器无法推断属性名称:
Anonymous Types (C# Programming Guide)
You must provide a name for a property that is being initialized with an expression (...)
您必须为正在使用表达式 (...) 初始化的属性提供名称