This runs in close to O(N) time:
var result = items.Distinct().ToList();
[EDIT]
Since there is no documented proof from Microsoft that it is O(N) time, I did some timings with the following code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Demo
{
class Program
{
private void run()
{
test(1000);
test(10000);
test(100000);
}
private void test(int n)
{
var items = Enumerable.Range(0, n);
new Action(() => items.Distinct().Count())
.TimeThis("Distinct() with n == " + n + ": ", 10000);
}
static void Main()
{
new Program().run();
}
}
static class DemoUtil
{
public static void TimeThis(this Action action, string title, int count = 1)
{
var sw = Stopwatch.StartNew();
for (int i = 0; i < count; ++i)
action();
Console.WriteLine("Calling {0} {1} times took {2}", title, count, sw.Elapsed);
}
}
}
The results are:
Calling Distinct() with n == 1000: 10000 times took 00:00:00.5008792
Calling Distinct() with n == 10000: 10000 times took 00:00:06.1388296
Calling Distinct() with n == 100000: 10000 times took 00:00:58.5542259
The times are increasing approximately linearly with n
, at least for this particular test, which indicates that an O(N) algorithm is being used.