1

我有一个包含以下值的折线列表(我通过查询 access 2007 表获得);

+----------+----------+----------+-------+
| ObjectID | VertexId | distance | angle |
+----------+----------+----------+-------+
|        1 |        0 |       10 |    45 |
|        1 |        1 |       10 |    44 |
|        1 |        2 |       20 |    60 |
|        2 |        0 |        5 |    35 |
|        2 |        1 |        6 |    35 |
|        2 |        2 |        4 |    56 |
|        2 |        3 |       12 |    45 |
|        3 |        0 |       20 |    30 |
|        3 |        1 |       10 |    12 |
+----------+----------+----------+-------+

正如 ObjectId 列所示,只有三个对象。我想将上面列表中的项目转换为以下格式的类..

Class Polyline
{
    int ObjectID;
    list<int> vertices;
    list<double> distances;
    list<double> angles;
}

这样我就可以保存折线对象列表并遍历每个唯一的折线,如下所示..

foreach(Polyline polyObj in Polylines)
{
    //do something with the polyline object;

}

在 C# 中执行此操作的最佳/快速方法是什么?它闻起来有 Linq 的味道 ..我是 linq 的新手,虽然非常渴望学习和使用它..

4

2 回答 2

1

假设您的折线列表是DataTable包含所有值的:

List<Polyline> polylines =
    tblPolyline.AsEnumerable()
   .GroupBy(p => p.Field<int>("ObjectID"))
   .Select(grp => new Polyline()
   {
       ObjectID = grp.Key,
       Vertices = new List<int>(grp.Select(p => p.Field<int>("VertexId"))),
       Distances = new List<double>(grp.Select(p => p.Field<double>("distance"))),
       Angles = new List<double>(grp.Select(p => p.Field<double>("angle"))),
   }).ToList();
于 2012-05-14T07:24:59.373 回答
1

考虑将顶点移动到单独的类:

public class PolyLine
{
    public PolyLine(int id, IEnumerable<Vertex> vertices)
    {
        Id = id;
        Vertices = new List<Vertex>(vertices);
    }

    public int Id { get; private set; }
    public List<Vertex> Vertices { get; private set; }
}

public class Vertex
{
    public Vertex(int id, int distance, int angle)
    {
        Id = id;
        Distance = distance;
        Angle = angle;
    }

    public int Id { get; private set; }
    public int Distance { get; private set; }
    public int Angle { get; private set; }
}

这是创建折线的 LINQ:

var polylines = from r in records
                group r by r.ObjectID into g
                select new PolyLine(g.Key, g.Select(r => new Vertex(r.VertexId, r.Distance, r.Angle)));

更新:LINQ to DataSet 版本

var polylines = from r in table.AsEnumerable()
                group r by r.Field<int>("ObjectID") into g
                select new PolyLine(g.Key, 
                             g.Select(r => new Vertex(r.Field<int>("VertexId"),
                                                      r.Field<int>("distance"), 
                                                      r.Field<int>("angle"))));
于 2012-05-14T07:25:42.527 回答