Skip to main content

UniqueNonSetCollection

Diagnostic Rule Overview​

FieldValue
IDSHIMMER1102
Analyzer titleUse a set instead
Analyzer messagePrefer sets when uniqueness is required
Code fix titleReplace .Distinct().ToList() or .Distinct().ToArray() with .ToHashSet()
Default severityInfo
Minimum framework/language version.NET Core 2.0+, .NET Framework 4.7.2+, .NET Standard 2.1
Enabled by default?No
CategoryShimmeringUsage
Link to codeUniqueNonSetCollectionAnalyzer.cs
Code fix exists?Yes

Detailed Explanation​

Using .Distinct().ToArray() or .Distinct().ToList() suggests that the goal is to remove duplicates. A HashSet<T> is a data structure that may better fit your use case, as it achieves the same outcome more efficiently while allowing a faster lookup.

Examples​

Flagged code:

using System.Collections.Generic;
using System.Linq;

namespace Tests;
class Test
{
void Do()
{
List<int> numbers = [];
var distinctNumbers = numbers.Distinct().ToArray();
}
}

Fixed code:

using System.Collections.Generic;
using System.Linq;

namespace Tests;
class Test
{
void Do()
{
List<int> numbers = [];
var distinctNumbers = numbers.ToHashSet();
}
}

Justification of the Severity​

This diagnostic is disabled by default because this diagnostic can cause compilation errors, which can be disruptive.

When to Suppress​

Suppress this diagnostic if changing the type breaks an existing contract or you need the collection to be ordered or indexed.

Inspiration​

Suggested by @matthew-elgart.