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