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?
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.
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.
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.
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.
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 (...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With