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

时间:2021-10-06 07:00:28

Thanks for looking

谢谢你的期待

My data

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

My linq statement

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

I am needing the only one occurrence of the Street, Town, postcode and then eastings and northing to go with that one record. I am not concerned with which record that is selected. Is this done with a groupby? I have been messing around with this with groupby but cannot figure it out. hope you can help

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

1 个解决方案

#1


3  

Then use a group by, and take for example the first item in the group

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

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

or in your case

或者在你的情况下

.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
});

#1


3  

Then use a group by, and take for example the first item in the group

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

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

or in your case

或者在你的情况下

.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
});

相关文章