dotnet / dotnet/winforms

Add version of ListViewItemCollection.AddRange() which accepts IList.

Open
#10,924 14 comments 0 reactions 2 assignees Claimed by @lonitra View on GitHub
api-suggestion waiting-on-team
Dominant language
C#
Stars
4.9k
Forks
1.1k
Avg merge
20h 23m
Merged PRs (30d)
103

Description

### Background and motivation

Currently when I call ``ToArray()`` on an ``List`` to then add the items in bulk in this way:

```cs
var sourceEntries = new List();
Array.ForEach(
SettingsFile.SettingsJson.Sources,
(x) => sourceEntries.Add(
new ListViewItem(
new string[]
{
x,
},
-1)));
this.ListView2.Items.AddRange(sourceEntries.ToArray());
```
This then generates a warning for the usage of ``ToArray()`` saying the inititialization can be simplified to:

```cs
this.ListView2.Items.AddRange([.. sourceEntries]);
```
Which compiles in the IDE, however when doing command line compiles via ``dotnet build -c Release`` this results in:
```
error CS0121: The call is ambiguous between the following methods or properties: 'ListView.ListViewItemCollection.AddRange(ListViewItem[])' and 'ListView.ListViewItemCollection.AddRange(ListView.ListViewItemCollection)'
```

As such a better option would be to add a version of ``AddRange`` that accepts ``List`` would be a great addition to the API and help fix this problem as well.

### API Proposal

```csharp
using System.Collections.Generic;

namespace System.Windows.Forms;

public partial class ListView
{
///
/// Represents the collection of items in a ListView or ListViewGroup
///
[ListBindable(false)]
public partial class ListViewItemCollection : IList
{
public void AddRange(List items);
}
}
```

### API Usage

```csharp
var sourceEntries = new List();
Array.ForEach(
SettingsFile.SettingsJson.Sources,
(x) => sourceEntries.Add(
new ListViewItem(
new string[]
{
x,
},
-1)));
this.ListView2.Items.AddRange(sourceEntries);
```

### Alternative Designs

Change the existing ``ListViewItemCollection`` overload of ``AddRange`` to also include all types that inherit from ``IList`` like ``List`` for example.

### Risks

Minimal, since it deals with adding ListViewItems from a ``List`` type of collection.

### Will this feature affect UI controls?

I think this would minimally affect them.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.