c# - 将条目添加到 IEnumerable
问题描述
我有一个复杂的 IEnumerable 遍历线段,以便前一段的终点与下一段的起点相同。我想按顺序提取点数组,不重复。所以它必须拾取第一段的起点,然后每个中点一次,最后是最后一段的终点。
我想出的是
Class Segment
{
public Vector Start { get; set; }
public Vector End { get; set; }
...
}
Class Path
{
...
public void Trace(IEnumerable<Segment> Route)
{
Vector[] Points = new List<Vector>() { Route.First().Start }.Concat(from segment in Route select segment.End).ToArray();
...
}
}
除了最后一个之外的Route[i].End = Route[i+1].Start
所有位置(如果 Route 是可索引的) 。i
虽然这有效(我认为 - 我还没有测试它),但对我来说似乎相当笨重。我讨厌为了开始这个过程而必须创建一个单一条目的列表。有没有更高效或优雅的解决方案?
(编辑:最初我有“Union”而不是“Concat”。)
解决方案
您可以编写一个简单的扩展方法。
public static IEnumerable<T> Prepend<T>(this T source, T item)
{
yield return item;
foreach (T t in source) yield return t;
}
要使用它:
public void Trace(IEnumerable<Segment> Route)
{
var item = from segment in Route select segment.End;
Vector[] points = Route.Prepend(item).ToArray();
}
推荐阅读
- spring - 从 Rest Api 调用 Spring Stomp Websocket 不起作用
- django - 三引号中的 Django 原始 sql 插入查询:Django 将 ajax 请求数据中的空值解释为 None 列
- python - 我想在 colab 中使用 imshow(),但它不起作用
- python-3.x - Concox GT800 / Wetrack800 GPS设备数据解码
- java - 如何填充可变参数构造器取消 applicationContext bean?
- json - 如何以编程方式查找 LUKS 标头的开始和结束字节?
- ios - 仍然收到警告“App Store 团队已弃用 API 使用”
- angularjs - 离线持久性在 AngularJS 的 Cloud Firestore 中不起作用(如何调试?)
- java - 为什么这个嵌套的for循环会无限循环(java)?
- matlab - MATLAB中的视频播放器,按住滑块控件