【问题标题】:Use LINQ to get comma separated list from different table使用 LINQ 从不同的表中获取逗号分隔的列表
【发布时间】:2014-04-06 23:15:30
【问题描述】:

我正在使用 ASP.NET 并且有一个 GridView,我想用 2 个表中的数据填充它。现在,我有以下查询:

var carListData = from x in db.cars
                  orderby x.carName
                  select new { x.carId, x.carName, locationIDs = string.Empty };
carList.DataBind();

现在,我想将 locationIDs 设置为逗号分隔的字符串。我需要查找销售每辆车的所有位置。我有一个名为 db.locationCars 的表,它有一个 locationId 列和一个 carId 列。多个位置可以具有相同的 carId。如何更新我的 carDataList 查询以获取销售每辆车的所有位置,以便这些 locationID 可以显示在 carList 网格视图中?

感谢您的任何建议!

【问题讨论】:

    标签: c# mysql asp.net sql linq


    【解决方案1】:

    使用GroupJoin 应该可以。如果第一个为您提供 SQL 问题的翻译,请尝试第二个。

    var carListData = db.cars
                        .GroupJoin(db.locationCars,
                                  (o,i) => o.carId,
                                  (o,i) => i.carId,
                                  (o,i) => new { o.carId, o.carName, locationIds = string.Join(",", i.Select(l => l.locationId)))
                        .OrderBy(g => g.carName);
    

    在内存中执行字符串连接的版本

    var carListData = db.cars
                        .GroupJoin(db.locationCars,
                                  (o,i) => o.carId,
                                  (o,i) => i.carId,
                                  (o,i) => new { o.carId, o.carName, locations = i.Select(l => l.locationId))
                        .OrderBy(g => g.carName)
                        .ToList()
                        .Select(g => new { g.carId, g.carName, locationIds = string.Join(",", g.locations));          
    

    【讨论】:

      【解决方案2】:
      foreach( var car in carList )
              {
                  var locationIds = Locations.Where( loc => loc.CarId == car.Id ).Select( loc => loc.Id );
                  car.locationIDs = string.Join( ",", locationIds );
              }
      

      【讨论】:

        【解决方案3】:

        如果您的外键在数据库中正确定义,并且您的实体框架模型使用这些外键更新。然后,您将在每个 Car 对象中拥有一个 locationCars 集合,其中包含您需要的 locationIds。

        创建一个名为 carListData 的新对象并选择该对象。此对象可以将您的 LocationCars 集合转换为 locationIds 的 csv。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-06
          相关资源
          最近更新 更多