0

I have an initial query that I want to modify to increase granularity in my results. But Visual Studio tells me my query isn't valid and I can't understand why. Basically I want to group my data according to 2 property (columns) and also group one of the property by the first N characters.

Initial query that works:

List<PostalCode> codes = (from customer in bd.Customers
                        group customer by customer.postalcode.Substring(0, postalCodeLength) into postalCodes
                        select new PostalCode
                        {
                            Postal = postalCodes.Key,
                            Count = postalCodes.Count()
                        }).ToList();
                return codes;

Query marked by ** as wrong by VS2010:

List<PostalCode> codes = (from customer in bd.Customers
                          group customer by new { **customer.postalcode.Substring(0, postalCodeLength)**, customer.CustomerGroupType}
                          into postalCodes
                          select new PostalCode 
                          { 
                                Postal = postalCodes.Key.postalcode,
                                CustomerGroupType = postalCodes.Key.CustomerGroupType,
                                Count = postalCodes.Count() 
                          }).ToList();
 return codes;

1 Answer 1

2

The new { } object syntax requires that properties have names - something your original query did not require. It cannot infer a name from your method call. So I'd recommend changing it to something like:

from customer in bd.Customers
group customer by new { TrimmedPostalCode = customer.postalcode.Substring(0, postalCodeLength), customer.CustomerGroupType}
into postalCodes
select new PostalCode 
{ 
    Postal = postalCodes.Key.TrimmedPostalCode,
    CustomerGroupType = postalCodes.Key.CustomerGroupType,
    Count = postalCodes.Count() 
}
2
  • Indeed, this worked. My question to you now, is why does the second property not require a a name?
    – guiomie
    Commented Jun 5, 2013 at 0:20
  • 1
    The compiler is able to infer the name because it's just a property, not a method call. If you think of it, the compiler can only see the "last thing" that happened in the first case - it just sees a "Substring Method Was Called That Returns a String" - it can't see what property Substring was called on. Commented Jun 5, 2013 at 0:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.