csharp list find index

Code Example - csharp list find index

                
                        // given list1 {3, 4, 6, 5, 7, 8}
list1.FindIndex(x => x==5);  // should return 3, as list1[3] == 5;
                    
                
 

index of item in list csharp

                        
                                List<string> strings = new List<string>(){"bob","ate","an", "apple"};
strings.IndexOf("bob");
//returns 0 
strings.IndexOf("an");
//returns 2
strings.IndexOf("apple");
//returns 3
strings.IndexOf("banana");
//returns -1
//Because banana is not in the list, IndexOf() returns -1
                            
                        
 

csharp findindex

                        
                                // Lets say you have an object with tha name of 'Role' nad it has parameters
// 'Name' & 'Id'

List<Role> roles = new List<Role>();
roles.Add(new Role() { Name = "Admin", Id = 1 });
roles.Add(new Role() { Name = "User", Id = 2 });

// Using a lambda expression we can find the index of a role
// with a specific text:

int roleIndex = roles.FindIndex(
	// Note that you can also use the index if youd like
	role => role.Name == "Admin"
);

// This can also be done using a variable from outside
// the lambda expression: 

string name = "Admin";
int roleIndex = roles.FindIndex(
	// Note that you can also use the index if youd like
	role => role.Name == "name
);

if (roleIndex > -1)
{
    Console.log(%%%~COMPRESS~PRE~2~%%%quot;Role {roles[roleIndex].Name} +
                was found at index {roleIndex}");
}
                            
                        
 

csharp find all indexes

                        
                                public static int[] FindAllIndexOf<T>(this T[] array, Predicate<T> filter)
        {
  			// Note: If select does not find a match returns index as "-1"
            int[] indexes = array.Select((elementInArray, index) => filter(elementInArray) ? index : -1)
                                 .Where(index => index != -1).ToArray();

            return indexes;
        }