通过起始和结束索引获取List<Item>的一部分

19

这是可能的吗?

例如,如果我有

List<Item> myList = new List<Item>;

//added 100 of Items to myList

//then I want to grab items at indices 50 - 60

List<Item> myNewList = myList.?

我怎么在不循环遍历myList的情况下做到这一点?

4个回答

46

4
可能OP希望有11个物品;) - Mare Infinitus
遗憾的是,这不适用于 IListIReadOnlyList - Arek

8
var myNewList  = myList.Skip(50).Take(10);

阅读“skip”和“take”的文档后,它们似乎使用基础的IEnumerable逻辑。这是否意味着性能为O(跳过的项目数)?也就是说,跳过100比跳过50慢吗? - Ted Spence
1
@TedSpence 是的,必须是这样。不确定是否执行了特定的优化,例如检查基础IEnumerable是否为IList等。从这些链接中看起来并不是这样,它们说对于较大的集合,List<T>.GetRange将更有效:https://icodeit.wordpress.com/2012/08/27/performance-of-skip-and-take-in-linq-to-objects/,http://geekswithblogs.net/BlackRabbitCoder/archive/2012/03/29/c.net-little-wonders-skip-and-take.aspx - nawfal


1

这个怎么样:

        List<string> myList = new List<string>();

        //added 100 of Items to myList
        for (int i=0; i<100; ++i)
        {
            myList.Add("blablabla");
        }

        //then I want to grab items at indices 50 - 60
        // Note: 50 - 60 inclusivly are actually 11 items
        List<string> myNewList = myList.GetRange(50, 11); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接