【问题标题】:Linq to Sql, group by 2 property and substringLinq to Sql,按 2 属性和子字符串分组
【发布时间】:2013-06-05 00:06:41
【问题描述】:

我有一个初始查询,我想修改它以增加结果的粒度。但是 Visual Studio 告诉我我的查询无效,我不明白为什么。基本上我想根据 2 个属性(列)对我的数据进行分组,并按前 N 个字符对其中一个属性进行分组。

有效的初始查询:

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;

由 ** 标记的查询被 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;

【问题讨论】:

    标签: c# .net linq linq-to-sql


    【解决方案1】:

    新的 { } 对象语法要求属性具有名称 - 这是您的原始查询不需要的。它无法从您的方法调用中推断出名称。所以我建议将其更改为:

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

    【讨论】:

    • 确实,这行得通。我现在问你的问题是,为什么第二个属性不需要名称?
    • 编译器能够推断名称,因为它只是一个属性,而不是方法调用。如果你想一想,编译器只能看到第一种情况下发生的“最后一件事”——它只看到“调用了返回字符串的子字符串方法”——它看不到调用了哪个属性 Substring。
    猜你喜欢
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    相关资源
    最近更新 更多