Android Question Basic question on List

Yayou49

Active Member
Licensed User
Hi,

Because i'm using Linq in dotnet, I have problem with basic list in B4a....

Well, suppose I have a list like:
list.add("Item1") (so index = 0)
list.add("Item2") (so index = 1)
list.add("Item3") (so index = 2)

How to retrieve Index of list if I have only item name = "Item2" ?

If I want to retrieve name from list with index, I can set:
Dim a as object = list.get(0)
MyName = a.name
and then I can retrieve a.name for exemple

But If I have Name = "item1", How to retrieve lst.id ?

Hope my question is clear enough ....
 

DonManfred

Expert
Licensed User
Longtime User
B4X:
    Dim l As List
    l.Initialize
    l.add("Item1") '(so index = 0)
    l.add("Item2") '(so index = 1)
    l.add("Item3") '(so index = 2)
   
    'How to retrieve Index of list if I have only item name = "Item2" ?
    Log(l.IndexOf("Item2"))
 
Upvote 0

Yayou49

Active Member
Licensed User
Thanks for your reply.
Your exemple works fine.

But I have another exemple and in this case, it doesn't work:

B4X:
Type Struct(Id As Int,libelle As String)
Dim lst As List
lst.Initialize
Dim Var1 As Struct
Var1.Id = 7
Var1.libelle = "item3"
lst.Add(Var1)
Dim Var1 As Struct
Var1.Id = 15
Var1.libelle = "item1"
lst.Add(Var1)
Dim Var1 As Struct
Var1.Id = 2
Var1.libelle = "item2"
lst.Add(Var1)

Log(lst.IndexOf("item2"))

What can be the solution in this case ?

A first solution can be to add:
B4X:
Dim lst2 As List
lst2.Initialize
For i = 0 To lst.Size - 1
Dim var2 As Struct
var2 = lst.Get(i)
lst2.Add(var2.libelle)
Next

and then Log(lst.IndexOf("item2"))

Is there another solution ?
 
Last edited:
Upvote 0

udg

Expert
Licensed User
Longtime User
You could use a map and traverse its Values collection with the For each statement.
In your case I guess that 'id' in struct is unique so it could play the index role for the map.
If the libelle item is unique too, then use it as index and make use of map.containsindex.

Why a map? Because if it is applicable to your case it is faster than a list.

udg
 
Last edited:
Upvote 0
Top