我有一个折线列表(通过查询访问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;
}
这样我就可以保存一条Polyline对象并在每条唯一折线上循环,如下所示。
foreach(Polyline polyObj in Polylines)
{
//do something with the polyline object;
}
在C#中执行此操作的最佳/最快方法是什么?它闻起来Linq ..我是linq的新手,虽然非常渴望学习和使用它..
答案 0 :(得分: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();
答案 1 :(得分: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"))));