LINQ Union - 字符串保持有序

LINQ Union - string keep orderby

return new List<string> { newItem }.Union(currentList.Take(9));

如何让 newItem 保持在顶部?这看起来很简单,但我的大脑冻结了。

它自然地对字符串进行排序,这意味着我的 newItem 可以出现在列表中的任何位置。我 currentList.Remove(newItem); 以防万一它已经在那里了。

尽量用Concat代替Union,前者保持顺序,后者是set方法,去重不保证顺序:

return new List<string> { newItem }.Concat(currentList.Take(9));

这适用于 Linq-To-Objects,如所述 here:

When the object returned by this method is enumerated, Union enumerates first and second in that order and yields each element that has not already been yielded.

但它也适用于数据库驱动的 LINQ 提供程序,如 Linq-To-SqlLinq-To-Entities,因为 UNION ALLUNION 表现相似(前者保持秩序,后者不保持秩序) .