gpt4 book ai didi

c# - 带有 Prev/Next 的 IEnumerable

转载 作者:太空狗 更新时间:2023-10-29 23:09:14 26 4
gpt4 key购买 nike

只是在寻找对此的一些确认。我需要为我的列表捕获上一个和下一个 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();

最佳答案

您可以编写一些辅助扩展来消除对结果数组的需求

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

然后建立你的结果看起来像这样

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

关于c# - 带有 Prev/Next 的 IEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771010/

26 4 0