Chen Chen Chen Chen - 21 days ago 5
C# Question

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

In C++, one can initialize a vector as

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


In additions, there is something like

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


Is there something similar in C# for List?

Answer

You can do this like this by 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