score:6

Accepted answer

i think maybe you can change the line

return (index + 1 == items.count) ? items[0] : items[index + 1];

for something like

return items[(index + 1) % items.count];

score:0

you can use the mod operator to simplify this a bit and combine everything into one statement:

return items[((string.isnullorwhitespace(curr) 
                ? 0 
                : items.indexof(curr)) + 1) % items.count]

its definitely shorter, but i'm not sure weather its more readable, too :)

score:0

i think the best solution is in the below link, i tried it out and works like charm.

http://www.dotnetperls.com/sort-list

score:1

i can see some optimization if you track the current index rather than the current string, but to do that the list of items would have to be fixed, i.e. not change.

you could also return items[(index + 1) % items.count];

otherwise that code looks fine to me, but perhaps someone has a more clever solution.

score:1

linq is not the appropriate tool here.

it sounds as if a linkedlist<t> would be the better collection here:

var linkeditems = new linkedlist<string>(items);
linkedlistnode current = linkeditems.find("c");
string afterc = current.next == null ? linkeditems.first.value : current.next.value;

here are the pros and cons of a linkedlist compared to a list.

score:1

a linq way:

var result = (from str in list
              let index = list.indexof(curr) + 1
              select list.elementatordefault(index) ?? list[0]).first();

score:7

the solution you have is functionally correct but it's performance leaves a little to be desired. typically when dealing with a list style structure you would expect that getnext would return a result in o(1) time yet this solution is o(n).

public sealed class wrappingiterator<t> {
  private ilist<t> _list;
  private int _index;
  public wrappingiterator<t>(ilist<t> list, int index) {
    _list = list;
    _index = index;
  }
  public t getnext() {
    _index++;
    if (_index == _list.count) {
      _index = 0;
    }
    return _list[_index];
  }

  public static wrappingiterator<t> createat(ilist<t> list, t value) {
    var index = list.indexof(value);
    return new wrappingiterator(list, index);
  }
}

the initial call to createat is o(n) here but subsequent calls to getnext are o(1).

ilist<string> list = ...;
var iterator = wrappingiterator<string>.createat(list, "b");
console.writeline(iterator.getnext());  // prints c
console.writeline(iterator.getnext());  // prints a
console.writeline(iterator.getnext());  // prints b

Related Query

More Query from same tag