-2

I declaring an array of linked list in C# and now i want to remove an element in index i that i not equal to first or last. How can i do it???

LinkedList<DataTable>[] Arraylinked= new LinkedList<DataTable[1000];                       
Arraylinked[0].AddLast(data table11);                 
Arraylinked[1].AddLast(data table12);
Arraylinked[2].AddLast(data table13);
Arraylinked[3].AddLast(data table14);

Now, I want to remove Arraylinked[2] in my arraylinkedlist. How can do it???

  • 2
    Did you even look at the documentation? http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx – Justin Pihony Jun 03 '13 at 15:43
  • Are you even sure you want a `LinkedList`? Why not just a standard `List`? – Arran Jun 03 '13 at 15:44
  • one shouldn't really use index's to access elements of `LinkedList`. – Mayank Jun 03 '13 at 15:45
  • 3
    he's not using a linked list - he's using an array of Linkedlist – Dave Bish Jun 03 '13 at 15:47
  • How does it looks like an array of linked lists? It's more linked list of data tables? – hackp0int Jun 03 '13 at 16:17
  • @IamStalker It's an array of linked lists of data tables. Notice the `[]` after the `LinkedList` declaration, that means it's an array, of linked lists. Linked lists are of course generic, meaning they're linked linked lists of something else. In this case, data tables, not that it would change the question for them to be linked lists of something else. – Servy Jun 03 '13 at 16:35
  • I'd suggest you to look here: http://stackoverflow.com/questions/457453/remove-element-of-a-regular-array. This should helps you to solve your problem in more efficient way then using loops. – Vlad Jun 03 '13 at 16:02
  • @Servy ohhh cheee haven't noticed the [] array sorry! – hackp0int Jun 03 '13 at 20:18

2 Answers2

0
DataTable node = Arraylinked.First;
int index = 0;
while (node != null) {
    DataTable nextNode = node.Next;
    if (index == 2) {
        Arraylinked.Remove(node);
    }
    node = nextNode;
    index++;
}

Or you can use the same code with different condition for removing items by its reference without knowing index.

Martin Perry
  • 9,232
  • 8
  • 46
  • 114
0

You can't "remove" from an array.

You can try to filter out by index, using Linq:

Arraylinked = Arraylinked
    .Where((idx, item) => idx != 2)
    .ToArray();

This incurs the cost of creating a brand-new array, however.

Dave Bish
  • 19,263
  • 7
  • 46
  • 63
  • 1
    Not my DV, but generally you'll want to change the data structure from an array to something else if you need this functionality rather than constantly re-creating the entire array each time you need to add/remove values. – Servy Jun 03 '13 at 16:00