IEnumerable与Prev/Next

and*_*eer 5 c# linq

只是在寻找一些确认.我需要捕获列表的上一个和下一个ID.有没有更好的办法?

var questionArray = dc.Question
    .Where(i => !i.IsDeleted)
    .OrderBy(i => i.SortOrder)
    .Select(i => new
    {
        i.QuestionID,
        i.Name,
    })
    .ToArray();

var questionList = questionArray
    .Select((item, index) => new
    {
        item.QuestionID,
        PrevID = index > 0 ? questionArray[index - 1].QuestionID : (int?)null,
        NextID = index < questionArray.Length - 1 ? questionArray[index + 1].QuestionID : (int?)null,
        item.Name,
    })
    .ToList();
Run Code Online (Sandbox Code Playgroud)

Mer*_*OWA 6

您可以编写一个小助手扩展来删除需要一个结果数组

public static IEnumerable<TResult> PrevNextZip<T, TResult>(this IEnumerable<T> stream, Func<T, T, T, TResult> selector) where T : class
{
  using (var enumerator = stream.GetEnumerator())
  { 
    if (enumerator.MoveNext())
    {
      T prev = null;
      T curr = enumerator.Current;

      while (enumerator.MoveNext())
      {
        var next = enumerator.Current;
        yield return selector(prev, curr, next);
        prev = curr;
        curr = next;
      }

      yield return selector(prev, curr, null);
    }
  }
} 
Run Code Online (Sandbox Code Playgroud)

然后构建您的结果将如下所示

  var questionList = questionArray.PrevNextZip((prev, item, next) => new
    {
      item.QuestionID,
      PrevID = prev != null ? prev.QuestionID : (int?)null,
      NextID = next != null ? next.QuestionID : (int?)null,
      item.Name,
    })
    .ToList();
Run Code Online (Sandbox Code Playgroud)