简体   繁体   English

如何使用linq将数组添加到list <>

[英]how to add array into list<> with linq

I have the following problem: the query with linq works ok, but I need to add the coordinates within an array for each record that is repeated 我有以下问题:使用linq的查询正常,但是我需要为重复的每个记录在数组内添加坐标

Model 模型

    public class AppPoisModel
    {
        public int idPoiType { get; set; }
        public string sector { get; set; }
        public double latPoint { get; set; }
        public double lngPoint { get; set; }
    }

Query 询问

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();

Result 结果

[
{
    "$id": "1",
    "sector" : "A",
    "latPoint": 0,
    "lngPoint": 0
},
{
    "$id": "2",
    "sector" : "A",
    "latPoint": 0,
    "lngPoint": 0
}
]

Desired result 所需结果

[
{
    "$id": "1",
    "sector" : "A",
    "coords": [{latPoint, lngPoint}, {latPoint, lngPoint}]
}
]

thank you very much for your contributions 非常感谢您的贡献

The initial query you suggested has no clue that there's a common relationship with items in the same sector. 您建议的初始查询不知道与同一扇区中的项目存在共同关系。

To accomplish this, you'll want to use the Enumerable.GroupBy() method to group those items together with the basis of having the same id and sector together. 为此,您将需要使用Enumerable.GroupBy()方法将这些项目分组在一起,并且具有相同的idsector

If both of those will always be correlated, you can just GroupBy() one of them to make the comparison simpler, but the results will also reflect that. 如果这两者始终保持关联,则可以只使用GroupBy()其中之一来简化比较,但结果也将反映这一点。

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 });

In your case, possibly with both id and sector . 就您而言,可能同时包含idsector This will be your key when you want to loop over the results. 当您要遍历结果时,这将是您的关键。 So that you can morph the results into the data type you want. 这样您就可以将结果变形为所需的数据类型。

looks like you need a group by... 看起来您需要一个...

Also you might create a class for Coords, and make AppPoisModel or a new result class, with a coords field typed as a collection of coords 另外,您可能会为Coords创建一个类,并制作AppPoisModel或一个新的结果类,并且将coords字段键入为coords的集合。

check it out: Group by in LINQ similar solution https://stackoverflow.com/a/47580961 签出: 在LINQ中按类似的解决方案分组 https://stackoverflow.com/a/47580961

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM