如何使用linq在一列上进行分组

时间:2014-02-04 09:27:53

标签: c# sql linq entity-framework group-by

感谢您寻找

我的数据

Easting          Northing         Street        Town        postcode
123454           887878           main          yourTown    gh6 0jh
098345           093978           main          yourTown    gh6 0jh
872982           873839           main          yourTown    gh6 0jh
849728           938393           south         yourTown    gh6 8uh
748494           817263           south         yourTown    gh6 8uh
989893           787878           high          yourTown    gh6 7mu
889955           992002           high          yourTown    gh6 7mu
882999           998339           high          yourTown    gh6 7mu

我的linq声明

return this._uow.Addresses
    .Where(a => a.Street.Trim().ToUpper().Contains(street.Trim().ToUpper()))
    .Select(a => 
        new Street() 
        { 
            MapEast = a.MapEast, 
            MapNorth = a.MapNorth, 
            Details = a.Street + " " + a.Town + " " + a.PostCode 
        })
    .AsEnumerable();

我需要街道,城镇,邮编的唯一一次出现,然后东向和北向与那条记录一起去。我不关心选择哪条记录。这是用groupby完成的吗?我一直在与群体搞乱,但无法弄明白。希望你能帮忙

1 个答案:

答案 0 :(得分:3)

然后使用group by,并以组中的第一项为例

.GroupBy(m => new {m.Street, m.Town, m.PostCode)
.Select(g => g.First());//You will get first Address

或在你的情况下

.Where(<yourWhereClause>)
.GroupBy(m => new {m.Street, m.Town, m.PostCode})
.Select(m => new Street {
       MapEast = m.FirstOrDefault().MapEast,//"random" MapEast
       MapNorth = m.FirstOrDefault().MapNorth,//"random" MapNorth
       Details = a.Key.Street + " " + a.Key.Town + " " + a.Key.PostCode
});