Reputation: 6668
I have a two lists, A & B. B contains say 100 elements. How do I add the 20th - 30th elements to list A from B. I know there is the AddRange but to me that looks like it would add all the elements from list B to list A. Is there a way to do this without using a loop?
Upvotes: 1
Views: 73
Reputation: 222722
You could use GetRange()
To get the elements from List A and then AddRange()
to add the elements to List B if they are of same type.
For example:
List<int> a = new List<int>();
List<int> b = new List<int>();
for (int i = 0; i < 100; i++)
{
b.Add(i);
}
List<int> sublist = a.GetRange(20, 10);
a.AddRange(sublist);
Upvotes: 3
Reputation: 66499
Assuming both lists have the same underlying type, you can use LINQ's Skip()
and Take()
methods to get the range of items you want from the second list:
var a = new List<string>();
// add 100 elements to a
var b = new List<string>();
// add 100 elements to b
a.AddRange(b.Skip(19).Take(11)); // add items 20 through 30 from b to a
Upvotes: 6