0

I have been trying to 'transport' the first two elements from list A to list B without copying them.

At the start, list A has four int values. In the end I want List A and B to both have 2 int values.

I'm trying something like this:

int a = 1;
int b = 2;
int c = 3;
int d = 4;

TestA.Add(a);
TestA.Add(b);
TestA.Add(c);
TestA.Add(d);

for (int i=0; i<2; i++)
{
    TestB.AddRange(TestA[i]);
}

I get a IEnummerable conversion error. I'm sure I'm doing it in a very naive way, and I'd appreciate some help here. Thanks.

Turbosheep
  • 183
  • 1
  • 2
  • 13
  • Where are you Declaring `TestB`? would help if you would add all relevant code..Please show how `TestA and TestB` are defined.. also why is there a `,` after `TestA[i],)` – MethodMan Apr 02 '13 at 21:41

1 Answers1

3

What's wrong with simple Take/Skip combination?

TestB = TestA.Take(2).ToList();
TestA = TestA.Skip(2).ToList();

Enumerable.Take - takes N elements from beginning of the collection.

Enumerable.Skip - skips N elements from beginning of the collection and takes all others.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • Thank you, that did the trick! I searched all over the internet for this, I'm wondering why I didn't find anything about this. Also, I'm curious, why is the method called 'skip'? What does it do? Thanks again! – Turbosheep Apr 02 '13 at 22:02
  • I've updated my answer with a little explanation. Hope it helped. – MarcinJuraszek Apr 02 '13 at 22:06
  • Thanks for all the help. But what if I add some elements back to A later on? Will it keep skipping over the first two elements? Because that'd be bad. Or do you mean that Skip() skips the first two, takes the others, and then rearranges the entire list to only have the values taken? – Turbosheep Apr 02 '13 at 22:12
  • Because there is `ToList()` call new `List` is created from all elements after first 2 (which are skipped). Changing the list content later has nothing to do with that `Take`/`Skip` here. – MarcinJuraszek Apr 02 '13 at 22:18