tags:

views:

102

answers:

5

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#.

+2  A: 

List(of T).IndexOf()

Strelok
Small side note: Since the question is tagged `C#`, it should better read [`List<T>.IndexOf(T)`](http://msdn.microsoft.com/en-us/library/8bd0tetb.aspx)
gehho
A: 

Simple Try this Suppose your list's name is objList; Then

int index = objList.IndexOf("B");
Johnny
he provide -1 but i need the index like 0 for a 1 for B 2 for C and 3 for D. are you know that.
steven spielberg
+6  A: 

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

Marc Gravell
+9  A: 

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.

PrateekSaluja
Good answer, this will surely work
Ankur Mukherjee
Thanks Ankur...
PrateekSaluja
A: 

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.

Turek