Get Index position of an element in a list in c#
int index = myList.FindIndex(a => a.Prop == oProp);
Get Index position of an element in a list in c#
int index = myList.FindIndex(a => a.Prop == oProp);
c# 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($"Role {roles[roleIndex].Name} +
was found at index {roleIndex}");
}
index of item in list C#
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
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us