Here is another solution without using a HashSet .
var items = new List<string>() { "one", "one", "two", "one", "two", "zero" }; var uniqueItems = items.Where((item, index) => items.IndexOf(item) == index);
It was adopted from this thread: javascript - unique values ββin an array
Test:
using FluentAssertions; uniqueItems.Count().Should().Be(3); uniqueItems.Should().BeEquivalentTo("one", "two", "zero");
Performance testing for List , HashSet and SortedSet . 1 million iterations:
List: 564 ms HashSet: 487 ms SortedSet: 1932 ms
Test source code (gist)
Alexey Solonets Aug 04 '16 at 10:55 on 2016-08-04 10:55
source share