您可以使用Aggregate
来构建列表。您构建的聚合跟踪最后一个元素以设置PrevID
在下一个元素中,并在NextID
插入新元素后立即更新最后一个元素。大约是这样的:
class Info { ... // QuestionID, PrevID, NextID, Name }
class ListBuilder { List<Info> list; Info lastElement; }
var questionList = dc.Question
.Where(i => !i.IsDeleted)
.OrderBy(i => i.SortOrder)
.Aggregate (
new ListBuilder () { list = new List<Info> (), lastElement = null },
(acc, source) => {
var lastElement = acc.lastElement;
var newElement = new Info () {
QuestionID = source.QuestionID,
PrevID = lastElement != null ? lastElement.QuestionID : null,
NextID = null
};
acc.list.Add (newElement);
if (lastElement != null) lastElement.NextID = source.QuestionID;
acc.lastElement = newElement;
return acc;
})
.list;
这保留了函数式编程的一些“精神”,但您也可以简单地使用闭包并在 linq 查询之前定义的局部变量中跟踪必要的信息。
或者为它构建一个函数:
IEnumerable<Info> previousNextInfo (IEnumerable<QuestionType> sourceEnumerable) {
Info preprevious = null;
Info previous = null;
Info current = null;
foreach (Info newOne in sourceEnumerable) {
preprevious = previous;
previous = current;
current = newOne;
yield return new Info () {
QuestionID = previous.ID,
lastID = preprevious != null ? preprevious.ID : null,
nextID = current.ID
};
}
if (current != null)
yield return new Info () { QuestionID = current.ID, lastID = previous.ID, nextID = null };
}
...
questionList = previousNextInfo (dc.Question
.Where(i => !i.IsDeleted)
.OrderBy(i => i.SortOrder)
).ToList ();