C# 如何将数组添加到列表中<&燃气轮机;与林克
我有以下问题:使用linq的查询工作正常,但我需要为每个重复的记录在数组中添加坐标 型号C# 如何将数组添加到列表中<&燃气轮机;与林克,c#,arrays,list,linq,entity-framework-6,C#,Arrays,List,Linq,Entity Framework 6,我有以下问题:使用linq的查询工作正常,但我需要为每个重复的记录在数组中添加坐标 型号 public class AppPoisModel { public int idPoiType { get; set; } public string sector { get; set; } public double latPoint { get; set; } public double lngPoint { get;
public class AppPoisModel
{
public int idPoiType { get; set; }
public string sector { get; set; }
public double latPoint { get; set; }
public double lngPoint { get; set; }
}
查询
var result = (from c in db.coord
select new AppPoisModel
{
idPoiType = c.id,
sector = c.sector,
latPoint = c.latitude ?? 0,
lngPoint = c.longitude ?? 0
}).ToList();
结果
[
{
"$id": "1",
"sector" : "A",
"latPoint": 0,
"lngPoint": 0
},
{
"$id": "2",
"sector" : "A",
"latPoint": 0,
"lngPoint": 0
}
]
[
{
"$id": "1",
"sector" : "A",
"coords": [{latPoint, lngPoint}, {latPoint, lngPoint}]
}
]
期望的结果
[
{
"$id": "1",
"sector" : "A",
"latPoint": 0,
"lngPoint": 0
},
{
"$id": "2",
"sector" : "A",
"latPoint": 0,
"lngPoint": 0
}
]
[
{
"$id": "1",
"sector" : "A",
"coords": [{latPoint, lngPoint}, {latPoint, lngPoint}]
}
]
非常感谢您的贡献您建议的初始查询没有线索表明与同一部门的项目存在共同关系 要实现这一点,您需要使用该方法将这些项目分组在一起,并以具有相同的
id
和扇区
为基础
如果这两个变量总是相关的,您可以选择其中一个来简化比较,但结果也会反映出这一点
var result = (from c in db.coord
select new AppPoisModel
{
idPoiType = c.id,
sector = c.sector,
latPoint = c.latitude ?? 0,
lngPoint = c.longitude ?? 0
}).GroupBy(x => new { id = x.idPoiType, sector = x.sector });
在您的情况下,可能同时使用
id
和sector
。当您想要循环结果时,这将是您的关键。这样您就可以将结果变形为所需的数据类型。看起来您需要一个分组依据
您还可以为Coords创建一个类,并创建AppPoisModel或一个新的结果类,其中Coords字段类型为Coords集合
请查看:
类似的解决方案您没有提供任何数据。因此,很难猜测您希望如何从该数据中获得结果。如果您在扇区
A
上分组,为什么仍然显示其中一个分组项的ID值?您天生就要隐藏任何附加ID,从而使ID属性的函数值变得无用。@HimBromBeere:您缺少什么信息?查询中的select语句似乎传递了四个相关字段所需的信息。此操作必须使用LINQ吗?如果不认真对待,查询将被转换为嵌套的SQL语句,这将增加复杂性和执行时间。我会选择使用EF或ADO.Net获取结果集,然后执行分组LINQ函数。您从哪里获取x.Field()
?类型AppPoisModel
只是具有公共属性。其次,您不能根据ID分组,因为两个POI的ID(在示例数据中)是不同的。链接到不同的问题(不直接回答问题)不是一个好方法。链接可能会丢失,使此答案在将来变得无用。将相关部分直接添加到您的答案中,并进行解释(注意:您可以保留链接作为附加参考)。我喜欢答案。它直接解释了零件,并添加了两个链接作为附加参考。当然,一行代码总是可以的;-)