Skip to content

Instantly share code, notes, and snippets.

@formix
Last active August 15, 2018 00:20
Show Gist options
  • Save formix/a079874d266ec389ae88cf92eefc4871 to your computer and use it in GitHub Desktop.
Save formix/a079874d266ec389ae88cf92eefc4871 to your computer and use it in GitHub Desktop.
The freaking .NET LinkedList<T> is broken since its inception (2.0). This implementation finally makes it an IList<T>.
using System;
using System.Collections.Generic;
namespace Formix.Fixes.Collections.Generic
{
public class FixedLinkedList<T> : LinkedList<T>, IList<T>
{
public T this[int index]
{
get
{
return GetAt(index).Value;
}
set
{
GetAt(index).Value = value;
}
}
public int IndexOf(T item)
{
int i = 0;
var node = First;
while (node!= null && !node.Value.Equals(item))
{
i++;
node = node.Next;
}
if (node == null)
{
return -1;
}
return i;
}
public void Insert(int index, T item)
{
AddBefore(GetAt(index), new LinkedListNode<T>(item));
}
public void RemoveAt(int index)
{
Remove(GetAt(index));
}
private LinkedListNode<T> GetAt(int index)
{
CheckIndex(index);
int i = 0;
var node = First;
while (i < index)
{
i++;
node = node.Next;
}
return node;
}
private void CheckIndex(int index)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException(
nameof(index),
"Parameter must be greater or equal than 0.");
}
if (index >= Count)
{
throw new ArgumentOutOfRangeException(
nameof(index),
"Parameter must be lower than the list items Count.");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment