首页 > 解决方案 > Linq 将多个结果放在一个地方

问题描述

我有一个 linq 查询,它从一个机场返回多个跑道,但问题是当我查找一个有多个跑道的大机场时,我一遍又一遍地得到相同的数据。无论如何我可以将所有低端和高端数据放入一个结果中所以我只能返回一个包含所有跑道的机场?数据库是MySql

LINQ查询

[HttpGet("search/{city}")]
public IActionResult Search(string city) 
{

    var res = (from airportTable in _dbContext.Airports
               join runwayTable in _dbContext.Runways on airportTable.Ident equals runwayTable.AirportIdent
               where airportTable.Municipality == city && airportTable.Type != "heliport" && airportTable.Type != "closed"

    select new
    {
        airportName= airportTable.Name,
        airportType = airportTable.Type,
        city = airportTable.Municipality,
        lowEnd = runwayTable.LeIdent,
        highEnd = runwayTable.HeIdent
    }).ToList();
    
    return Ok(res);
}

结果


{ airportName = Lansing Municipal Airport, airportType = small_airport, city = Chicago, lowEnd = 09, highEnd = 27 }

{ airportName = Lansing Municipal Airport, airportType = small_airport, city = Chicago, lowEnd = 18, highEnd = 36 }

我希望数据像这样返回,我想我可以使用 SelectMany 来做到这一点,但我不知道我必须把它放在哪里

{ airportName = Lansing Municipal Airport, airportType = small_airport, city = Chicago, lowEnd = 09,18, highEnd = 27, 36}

标签: mysqllinq

解决方案


您的 linq 有一个数据库作为源。我不知道它到底是什么类型的数据库,但我想它的 LINQ 库没有分组然后连接的翻译。因此,您可能必须按res原样处理您的输出,然后从那里使用它,例如下面我按机场级属性分组,然后连接跑道级属性:

var finalResult = 
    from r in res
    group r by new { r.airportName, r.airportType, r.city } into g
    select new { 
        g.Key.airportName,
        g.Key.airportType,
        g.Key.city,
        lowEnd = g.Select(r => r.lowEnd).Aggregate((x,y) => x + "," + y), 
        highEnd = g.Select(r => r.highEnd).Aggregate((x,y) => x + "," + y) 
    };

推荐阅读