首页 > 解决方案 > 将条目添加到 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”。)

标签: c#linq

解决方案


您可以编写一个简单的扩展方法。

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

推荐阅读