Skip to content

Instantly share code, notes, and snippets.

@jjwatt
Created November 3, 2020 03:02
Show Gist options
  • Save jjwatt/bb0788725f2aade1777092dc501a0096 to your computer and use it in GitHub Desktop.
Save jjwatt/bb0788725f2aade1777092dc501a0096 to your computer and use it in GitHub Desktop.
Messing with List<T> lists in C#
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace NUnitTestProject1
{
public class Tests
{
public List<String> Mystrs;
[SetUp]
public void Setup()
{
Mystrs = new List<string>();
}
[Test]
public void Test1()
{
Mystrs.Insert(0, "hello");
Mystrs.Insert(0, "world");
Console.WriteLine("list members:");
foreach (var aString in Mystrs)
{
Console.WriteLine(aString);
}
Assert.AreEqual("world", Mystrs[0]);
Assert.AreEqual("hello", Mystrs[1]);
Mystrs.RemoveAt(0);
// NOT FIFO
// insert hello -> insert world -> RemoveAt(world), then hello is still left
Console.WriteLine(Mystrs[0]);
Mystrs.Insert(0, "world");
Console.WriteLine(Mystrs[0]);
Assert.AreEqual("world", Mystrs[0]);
Assert.AreEqual("hello", Mystrs[1]);
// This is not a queue.
// A Queue would insert from one side and take from the other.
// Delete items and start again.
Mystrs.RemoveRange(0, 2);
// Above, "Insert(0, item)" inserts at the head and RemoveAt(0) removes from the head (Not FIFO)!
// Instead, it's "First In Last Out"
// To get queue behavior, add to the end and take from the head.
Mystrs.Add("hello");
Mystrs.Add("world");
// "pop"
var popped = Mystrs[0];
Mystrs.RemoveAt(0);
// Now, popped will be "hello" (i.e., "First In" is now "First Out").
Assert.AreEqual("hello", popped);
Console.WriteLine("Popped val: {0}", popped);
// "pop" again
popped = Mystrs[0];
Mystrs.RemoveAt(0); // Must remove during "pop" from a queue so you can always use head (or [0])
// Now, popped
Assert.AreEqual("world", popped);
Console.WriteLine("2nd Popped val: {0}", popped);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment