Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a list into another list in vb.net

Tags:

list

vb.net

I have a list as follows and I want to add it in another list:

Dim listRecord As New List(Of String)
listRecord.Add(txtRating.Text)
listRecord.Add(txtAge.Text)
listRace.Add(listRecord)  

to obtain something like {{r1,a1},{r2,a2},{r3,a3}}, how can I achieve this in VB.Net?

like image 471
Naad Dyr Avatar asked Feb 28 '12 08:02

Naad Dyr


3 Answers

You could use List's AddRange

listRace.AddRange(listRecord)

or Enumerable's Concat:

Dim allItems = listRace.Concat(listRecord)
Dim newList As List(Of String) = allItems.ToList()

if you want to eliminate duplicates use Enumerable's Union:

Dim uniqueItems = listRace.Union(listRecord)

The difference between AddRange and Concat is:

  • Enumerable.Concat produces a new sequence(well, actually is doesn't produce it immediately due to Concat's deferred execution, it's more like a query) and you have to use ToList to create a new list from it.
  • List.AddRange adds them to the same List so modifes the original one.
like image 58
Tim Schmelter Avatar answered Nov 09 '22 19:11

Tim Schmelter


I assume from your question you want nested Lists, not to simply append one list onto the end of another?

Dim listRecord As New List(Of String)
listRecord.Add(txtRating.Text)
listRecord.Add(txtAge.Text)
listRace.Add(listRecord)

Dim records as new List(of List(of String))
records.Add(listRecord)

Hope this helps

Update
Reading them is like accessing any other list.
To get the first field in the first record

return records(0)(0)

second field in first record

return records(0)(1)

etc . . .

like image 29
Binary Worrier Avatar answered Nov 09 '22 20:11

Binary Worrier


I have been looking for the same problem and I found the solution. I think this is exactly what you want (To set list items inline, instead of using functions of List(of()) class):

Dim somelist As New List(Of List(Of String)) From {New List(Of String) From {("L1 item1"), ("L1 item2")}, New List(Of String) From {("L2 item1"), ("L2 item2")}}

I admit that it looks complicated, but this is the structure.

In order to make the code look simpler, I add the following screen snip showing the code: https://www.dropbox.com/s/lwym7xq7e2wvwto/Capture12.PNG?dl=0

like image 1
MuhsinFatih Avatar answered Nov 09 '22 18:11

MuhsinFatih