簡體   English   中英

Lambda表達式與where子句,如何進行分組

[英]Lambda expression with where clause, how to do a group by

我有一個lambda表達式,該表達式返回我要查找的記錄,除了名稱不是唯一的以外,因此我需要按名稱分組,這就是我所擁有的,有人可以幫我這個忙。

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

您可以使用:

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之后使用。

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

.GroupBy(c => c.CityName)

您可以使用:

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
        }

這應該僅返回每個名稱的一個實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM