I have a list who have some element like A B C D. I want to get the index of B. How i can get it?
I want to do this in C#.
I have a list who have some element like A B C D. I want to get the index of B. How i can get it?
I want to do this in C#.
Simple Try this Suppose your list's name is objList; Then
int index = objList.IndexOf("B");
This can be as simple as:
int index = list.IndexOf(b);
where b is the thing to find, however there is an ambiguity here over the definition of equality. By default, classes will use reference-equality. I common mistake is creating two class instances that have identical fields, and expecting them to count as "equal". To do this, you should really override Equals (and ideally implement IEquatable<T> for the same T). And if you override Equals, you should also override GetHashCode, and ideally the ==/!= operators.
Another alternative is to find the match with a predicate or comparer, which can avoid all that work
Hello ,
Suppose you have 4 element like A,B,C,D.
List Char = new List(); Char.Add("A"); Char.Add("B"); Char.Add("C"); Char.Add("D");
int index = Char.IndexOf("B");
so the output will be 1.(index of B)
I hope this will help you.
Things get a little complicated when you have a list of complex types. You need to know that your list can have multiple objects with the same parameters, eg. there can be few "A" on the list. It all comes down to querying the list.
I often use, eg.
var results = (from i in people
where i.name == "Alexander" //here you put your predicate
select myList.indexOf(i));
or
var results = people.Where(p=>p.name == "Alexander"); //this gives You full objects, not indices
That way I have list of indices of all the people with name "Alexander". You can loop through it, get a single one or whatever.
Just remember that list can have multiple indices of the value you are looking for.