how to get the position of an element in a list in xamarin

Gerson Jose Rodriguez Quintero 51 Reputation points
2022-10-06T18:45:24.797+00:00

how to get the position of an element in a list in xamarin. for example:

List<double> lists = new List<double> { 80 , 90 , 102 , 99 }

if you search for "90" The result is position #2

if you search for "99" The result is position #4

Developer technologies | .NET | Xamarin
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2022-10-07T01:36:22.283+00:00

    Hello,

    You can use List<T>.IndexOf Method to the index. If you want to get the position, you need to add 1. Here is test code.

    I add Button click event for testing. If search result is exclude the List, you get -1 when you execute list.IndexOf();. I notice you search text is string, you need to use double.Parse("90") to convert it from string to double.

       public partial class MainPage : ContentPage  
           {  
               List<double> list;  
               public MainPage()  
               {  
                   InitializeComponent();  
                  list = new List<double>() {80,90, 102,99};  
               }  
              private void Button_Clicked(object sender, EventArgs e)  
               {     
                   var res=  list.IndexOf(double.Parse("90"));  
                  if (res != -1)  
                   {  
                       string ResPostion = "Postion#" + (res + 1);  
                       DisplayAlert("info", ResPostion, "OK");  
                   }  
                    
               }  
           }  
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.