3

How I can add in one step an Array of string into a Listview for example using LINQ or Casting methods?

This is what I've tried but does not work:

ListView1.Items.AddRange("a b c d e f".Split(" ").ToArray _
.Select(Function(x) New ListViewItem(x)))

UPDATE:

Another try, does not work:

ListView1.Items.AddRange( _
    New ListView.ListViewItemCollection( _
    {"Value 1", "Value 2", "Value 3"} _
   .Select(Function(x) New ListViewItem(x))))

4 Answers 4

4

AddRange expects an array but the Select function returns an IEnumerable. So you just have to add ToArray to the end of the expression. Since Split returns a string array there is no need to add a call to ToArray there.

This will do the job:

ListView1.Items.AddRange("a b c d e f".Split(" "c) _
                                      .Select(Function(x) New ListViewItem(x)) _
                                      .ToArray)
Sign up to request clarification or add additional context in comments.

2 Comments

@DanielNeel: No it can't. Select expects an argument of type Func(Of String, TResult). New ListViewItem(x) is of type ListViewItem. Besides that x is not defined.
Whoops, you're correct @pescolino. Should have looked at that more closely before posting - deleting my comment to prevent confusion.
2

It seems you have to set the first column with 'Items.Add' and the rest of the columns with 'SubItems.AddRange'. This is the code I use to accomplish that:

string[] arr = "column1|column2|column3".Split('|');
ListView1.Items.Add(arr[0]).SubItems.AddRange(new string[] { arr[1], arr[2] });

Comments

1
ListView1.Items.AddRange("a b c d e f".Split(" ".ToCharArray()))

The above should be the correct syntax in order to add those characters as the list

EDIT Think I missed the ListViewItem collection out

ListView1.Items.AddRange(new ListViewItem("a b c d e f".Split(" ".ToCharArray())))

1 Comment

Thanks but any of the two codes works, both throws exceptions... but also I've asked for a string array, not for a characters array, the character values I wrote were only to give an example, thanks anyway.
0

Done!

I hope this helps someone else:

  ' Set the Array content
  Dim Items As String() = "ABC DEF GHI JKL".Split

  ' Add them in one step
  ListView1.Items.AddRange(Items.Select(Function(x) New ListViewItem(x)).ToArray)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.