- SonarLint for Visual Studio 2019, v4.26.0.22454
- Sample code:
/// <summary>
/// Stupid example, but enough to demonstrate issue.
/// Actual use case was using Dapper to map 1:N relationship of actual POCO types
/// An example of this (but with an anonymous function) is found at https://dapper-tutorial.net/result-multi-mapping#example-query-multi-mapping-one-to-many
/// But I didn't want my example to have dependencies!
/// </summary>
/// <returns></returns>
public List<List<TValue>> GroupValues<TKey, TValue>(IEnumerable<ValueTuple<TKey, TValue>> inputs)
{
// example input: new List<(string, int)> { ("A", 1), ("A", 2), ("B", 3), };
// example output: new List<List<int>> { new List<int> { 1, 2, }, new List<int> { 3, } };
// Below line has S1854 warning ("useless assignment"), but it is actally captured and used in MapTuple function below
var workingMap = new Dictionary<TKey, List<TValue>>();
return inputs
.Select(MapTuple)
.Distinct()
.ToList();
// Obvious workaround (other than ignoring) would be to make this static and pass in workingMap, but that's not a clean option when passing as a Func<...> parameter expecting a certain signature
List<TValue> MapTuple((TKey key, TValue value) input)
{
if (!workingMap.TryGetValue(input.key, out var workingValue))
{
workingValue = new List<TValue>();
workingMap.Add(input.key, workingValue);
}
workingValue.Add(input.value);
return workingValue;
}
}
Not suggesting this is the cleanest way to implement something like this, but the S1854 warning is definitely invalid since the value assigned to workingMap
is used.