dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.29k stars 4.74k forks source link

Analyzer: change Enumerable.Concat with single element arrays into Append or Prepend #88314

Open huoyaoyuan opened 1 year ago

huoyaoyuan commented 1 year ago

Since Append and Prepend comes much later than Enumerable.Concat, there are many old code using Concat with single-element array:

values.Concat(new[] { moreValue })

which can be converted into:

values.Append(moreValue)

Prepend is less common, and changes the order of two elements in code, but it would be more natural.

Category: Performance Severity: Info

ghost commented 1 year ago

Tagging subscribers to this area: @dotnet/area-system-linq See info in area-owners.md if you want to be subscribed.

Issue Details
Since `Append` and `Prepend` comes much later than `Enumerable.Concat`, there are many old code using `Concat` with single-element array: ```csharp values.Concat(new[] { moreValue }) ``` which can be converted into: ```csharp values.Append(moreValue) ``` `Prepend` is less common, and changes the order of two elements in code, but it would be more natural. Category: Performance Severity: Info
Author: huoyaoyuan
Assignees: -
Labels: `api-suggestion`, `area-System.Linq`, `code-analyzer`, `code-fixer`
Milestone: -
campersau commented 1 year ago

Note that Enumerable.Append is not directly supported in net47 or older. https://apisof.net/catalog/6ae58543-a1b1-3617-8780-227339489ae8

huoyaoyuan commented 1 year ago

Note that Enumerable.Append is not directly supported in net47 or older.

Yes, it needs extra attention for netstandard2.0, since it requires a shim on net461-net47. For non-netstandard platforms, just detecting the existence of the methods should be sufficient.

huoyaoyuan commented 8 months ago

With collection expressions, there are actually additional options with spread: [..values, morevalue]. But maybe there are ones still prefer method call.