Lambda表达式用where子句,如何做一个group by

时间:2013-11-21 05:04:56

标签: c# lambda

我有一个lambda表达式,它返回我正在寻找的记录,除了名称不是明显的,所以我需要按名称分组,这是我所拥有的,有人可以帮我一把。< / p>

var cities = _context.country.OrderBy(c => c.Name)
            .Where(c => c.Feature_Code != featureCode
                && c.Feature_Code != featureCode2
                && c.Country_Code == CountryCode
                && c.Admin1_code == StateId)
            .Select(c => new CityViewModel
            {
                CityId = c.CountryID,
                CityName = c.Name
            }
        ).AsQueryable();

3 个答案:

答案 0 :(得分:1)

您可以使用:

var cities = _context.country
                     .Where(c => /*Your where conditions*/)
                     .GroupBy(c => c.Name)
                     .OrderBy(grp => grp.Key)
                     .Select(grp => new CityViewModel
                     {
                         CityId = grp.First().CountryID,
                         CityName = grp.Key
                     });

OrderBy应该在Where。

之后使用

答案 1 :(得分:0)

根据您的需要,您可以添加:

.GroupBy(c => c.CityName)

答案 2 :(得分:-1)

您可以使用:

var cities = _context.country.Distinct(c => c.Name).Where(c => c.Feature_Code != featureCode
            && c.Feature_Code != featureCode2
            && c.Country_Code == CountryCode
            && c.Admin1_code == StateId)
        .Select(c => new CityViewModel
        {
            CityId = c.CountryID,
            CityName = c.Name
        }

这应该只返回每个名称的一个实例。