如何纠正我的代码。在单个数组结果中简化我的答案

时间:2017-01-27 05:27:19

标签: c# linq

这是我的代码。我想知道如何将值存储在单个变量数组格式中。我不知道下一步。我是LINQ和C#的新成员。

var result = (from x in _context.DwPropertyMasters
   where
     x.ShowMapPoint == "Y"
   select new
     {
       x.LandId,
       a = x.Development == null || x.Development == "" ? x.Location : x.Development,
       x.MapPointX,
       x.MapPointY,
       AreaSize = x.AreaSize ?? 0,
       Premium = x.Premium ?? 0,
       b = (x.Premium == 0 ? null : x.Premium) * 100000000 / (x.AreaSize == 0 ? null : x.AreaSize),

       c = (from z in _context.DwPropertyDetails
           where (z.TransactionPrice > 0 || z.TransactionPrice != null) && z.LandId == x.LandId
           group z by z.LandId into g
           select (g.Sum(p => p.TransactionPrice) == 0 ? null : g.Sum(p => p.TransactionPrice)) / (g.Sum(p => p.ActualSize) == 0 ? null : g.Sum(p => p.ActualSize))).FirstOrDefault(),

           d = (x.AreaSize2 == 0 ? null : x.AreaSize2) == 0 ? 0 : (x.Premium == 0 ? null : x.Premium) * 100000000 / (x.AreaSize2 == 0 ? null : x.AreaSize2),
           x.LandType,
           e = (from y in _context.DwPropertyDetails
           where (y.TransactionPrice > 0 || y.TransactionPrice != null) && y.LandId == x.LandId
           select new
           {
             a = 1
           }).Count()
        }).ToArray();

        return View(result);

我得到的结果是这样的:

[
  {
    "LandId":1,
    "a":"2GETHER",
    "MapPointX":"22.37607871816074",
    "MapPointY":"113.96758139133453",
    "AreaSize":118046,
    "Premium":5.51,
    "b":4667.671924,
    "c":13198,
    "d":4148.815215,
    "LandType":"PROPERTY",
    "e":169
  }
]

我想要的就是这样:

[1,'2GETHER',22.37607871816074,113.96758139133453,118046,5.51,4668.00000000000000000000,13198,4149.00000000000000000000,'PROPERTY',169]

2 个答案:

答案 0 :(得分:2)

这样的东西?

return View(new object[] { 
    result.LandId,
    result.a,
    result.MapPointX,
    result.MapPointY,
    result.AreaSize,
    result.Premium,
    result.b,
    result.c,
    result.d,
    result.LandType,
    result.e
});

答案 1 :(得分:0)

当您执行以下操作时,只需稍微扩展一下devio之前的答案:

.Select( new { ... } ).ToArray()

您实际上是在告诉它为您提供一系列新动态创建的对象。创建动态对象时,它会自动为您导出属性名称。它最终看起来像一个键值对字典。您可以尝试强制它为您提供对象数组而不是动态类型。类似的东西:

var result = _context.DwPropertyMasters
   .Where( x => x.ShowMapPoint == "Y")
   .Select( x => new object[] { x.LandId, x.MapPointX, ... })
   .ToArray();

不同之处在于,不是要求它提供动态对象数组,而是要求它提供一个对象数组数组。