C#中List和C++中vector在初始化方面的比较

Comparison of List in C# and vector in C++ in terms of initialization

在 C++ 中,可以将向量初始化为

vector<int> nums1 (100, 4); // 100 integers with value 4

此外,还有类似

vector<int> nums2 (nums1.begin() + 5, nums1.end() - 20);

在 C# 中是否有类似的 List?

第一个是这样的:

var result = Enumerable.Repeat(4, 100);

第二个(我不熟悉 C++)是这样的(我想这意味着类似于从第 5 个元素到最后第 20 个元素):

var result2 = result.Skip(5).Take(75);

请注意,resultresult2 都只是迭代器,因此是惰性求值的。调用 ToListToArray 将通过执行查询实际实现集合。

您可以通过 List 这样做。

using System.Collections.Generic;
List<int> nums1 = new List<int>(Enumerable.Repeat(4,100)); //100 elements each with value 4
List<int> nums2 = new List<int>(nums1.Skip(5).Take(75)); // skip first 5 and take 75 elements