1

Let's say that I have a LinkedList< Client> and each Client object has an ID property. I want to set each client's ID according to their index in the LinkedList.

In Java i used to do it like this

 for (Client i : clientList)
 {              
    i.setClientId(clientList.indexOf(i));
 }

I can't seem to find an equivalent function of indexOf() in C#

apboutos
  • 109
  • 2
  • 16
  • I think the biggest question is, why are you using a linked list? You will probably find a better fit for your needs with another collection. And also, why would you want to id the client with the index in the list? This does not seem like a logical thing to do. – dmg_ Jun 30 '16 at 16:40
  • I used the Linked List collection mainly out of ignorance of other collections, as the main thing I wanted was a non static length array of objects. I want the index passed down to the Client object because I want to know which one is stored first, second etc, as I want to present them in an orderly manner to the user interface, where the user can change the index if he wants. – apboutos Jun 30 '16 at 16:45
  • You should google an overview of the Collection types and choose one that fits your needs before using it. LinkedList is what it is, it's linked as in -> the first object points to the next and the next to the next. You kinda chose the worst possible list for this since the list has no idea where the objects are - _Each node in a LinkedList object is of the type LinkedListNode. Because the LinkedList is doubly linked, each node points forward to the Next node and backward to the Previous node._ – dmg_ Jun 30 '16 at 16:52

2 Answers2

3

In Java i used to do it like this [...]

This is a slow option: the operation takes O(n2), because you perform a linear search for each element of clientList. A better option would be to keep an integer index outside the loop:

int lastId = 0;
for (Client i : clientList) {              
    i.setClientId(lastId++);
}

I can't seem to find an equivalent function of indexOf() in C#

That's good, because you can use a better option:

var lastId = 0;
foreach (var c in clientList) {
    c.ClientId = lastId++;
}

An option without local variable is more complex, but here it is anyway:

foreach (var p in clientList.Select((c, i) => new {Client=c, Index=i})) {
    p.Client.ClientId = p.Index;
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Try :

int i = 0;
foreach( Client c in clients){
   c.Id = i++;
}

IndexOf doesn't exist in LinkedList - it is a linked structure.

Finding the index of an element means comparing a searched element to all elements. It would be very inefficient.

Prefer List<Client> to LinkedList<T> if you can't run the loop.

And if you need to use LinkedList<T>, consider writing your own function and having lower performances.

Regards

Emmanuel DURIN
  • 4,803
  • 2
  • 28
  • 53