简体   繁体   English

从另一个列表创建一个列表,并按某些索引过滤

[英]Creating a List from another List, filtered by certain indexes

I have a List<decimal> and I want to create a new List<decimal> from a subset of the first List. 我有一个List<decimal> ,我想从第一个List的子集创建一个新的List<decimal>

Code example: 代码示例:

List<decimal> set1 = new List<decimal>() { 10, 20, 30, 40, 50 };

How do I create a new List that is from index=2 to index=4 (30, 40, 50)? 如何创建从index = 2到index = 4(30、40、50)的新列表?

var set2 = set1.Skip(2).Take(3).ToList();
var list = set1.Select((r, i) => new { Index = i, Value = r })
               .Where(t => t.Index >= 2 && t.Index <= 4)
               .Select(r => r.Value);

If you want to have a List you can append ToList to the query. 如果要拥有列表,可以将ToList附加到查询中。

For output 输出

foreach (var item in list)
{
    Console.WriteLine(item);
}

output: 输出:

30
40
50

Using GetRange 使用GetRange

var newlist = set1.GetRange(2,3);

You are passing starting index (2) and number of items you will get (3) 您正在传递起始索引(2)和您将获得的项目数(3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM