【问题标题】:how to groupby on only one column using linq如何使用 linq 仅对一列进行分组
【发布时间】:2014-02-04 09:27:52
【问题描述】:

感谢收看

我的数据

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完成的吗?我一直在用 groupby 解决这个问题,但无法弄清楚。希望你能帮忙

【问题讨论】:

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


    【解决方案1】:

    然后使用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
    });
    

    【讨论】:

    • 谢谢拉斐尔。 VS 告诉我使用FirstOrDefault() 而不是First()。但似乎正在工作
    • @Easty 哦,是的,永远忘记这个...即使这是一个永远不会为空的 FirstOrDefault...
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多