List中的 LINQ 项目范围

发布于 2024-10-03 14:17:25 字数 310 浏览 1 评论 0原文

使用 Linq,如何获取序数位置在 5 到 27 之间的对象列表。

MyObject 的数量未知,因此什么也找不到。

"allItems" 始终按顺序排列,因此需要序号位置。

像这样:

List<MyObject>  allItems = GetAllItems();
List<MyObject>  myRange = allItems.LINQSTATEMENTHERE(5 to 27th items);

Using Linq, how can I get a list of objects where their ordinal poistion is between 5 and 27.

There is an unknown number of MyObject, so somethings nothing could be found.

"allItems" is always in order so ordinal position is required.

Like this:

List<MyObject>  allItems = GetAllItems();
List<MyObject>  myRange = allItems.LINQSTATEMENTHERE(5 to 27th items);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

两仪 2024-10-10 14:17:25

使用 Skip() 和 Take() 的组合:

int from = 5;
int to = 27;
var myRange = allItems.Skip(from - 1).Take(to - from);

Use a combination of Skip() and Take():

int from = 5;
int to = 27;
var myRange = allItems.Skip(from - 1).Take(to - from);
浊酒尽余欢 2024-10-10 14:17:25

由于您需要立即执行(您希望将结果加载到列表中),因此这里不需要使用 LINQ;您可以使用实例 GetRange 方法List

List<MyObject> myRange = allItems.GetRange(from, to - from + 1);

当然,如果您想要延迟执行,或者希望该技术应用于其他类型的序列,请使用 Justin Niessner 的技术。他的技术的一个好处是,如果代表范围的元素太少,它就不会爆炸。

Since you require immediate execution (you want to load the results into a list), there's no need to use LINQ here; you can use the instance GetRange method on List<T>:

List<MyObject> myRange = allItems.GetRange(from, to - from + 1);

Of course, if you want deferred execution, or you want the technique to apply to other types of sequences, go with Justin Niessner's technique. The one benefit that his technique has is that it won't blow up if there are too few elements to represent the range.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文