Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
926 views
in Technique[技术] by (71.8m points)

c# - Invalid anonymous type member declarator

I have a problem with the following code which should work, according to 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)};
        }
    }
}

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.

What's wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to name the property used to store Sum method result:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...