Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid anonymous type member declarator

Tags:

c#

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?

like image 946
chhenning Avatar asked Sep 17 '13 18:09

chhenning


People also ask

What are anonymous types in C sharp?

Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.

Is VAR anonymous type in C#?

Understand anonymous types in C# Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.

What are anonymous types in Linq?

Anonymous types provide a convenient way to encapsulate a set of read-only properties in an object without having to explicitly define a type first. If you write a query that creates an object of an anonymous type in the select clause, the query returns an IEnumerable of the type.

What are anonymous data types?

Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.


1 Answers

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

like image 75
MarcinJuraszek Avatar answered Oct 02 '22 08:10

MarcinJuraszek