Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: (untagged)
Hi,
I need to find a index of Object/item stored in List<string>.
It contains about 250 items.

I used List<t>.findindex method, but i am not able to use Predicate delegate.
I have read many articles but i am not able to understand it.

Please help me finding the item in List<string>.

Here is piece of code.
System.Collections.Generic.List<string> AllRanks = new List<string>();


It contains eg:
1. ABC
2. BBC

Thanks in advance.
Posted

Better code would be using anonymous method:

C#
System.Collections.Generic.List<string> list =
    new System.Collections.Generic.List<string>();

//...

int index = list.FindIndex(new System.Predicate<string>(
    (value) => {
        return value == "ABC" || value == "BBC";
}));


—SA
 
Share this answer
 
Comments
prathameshpitale 16-May-11 6:14am    
Thanx!
Sergey Alexandrovich Kryukov 16-May-11 6:23am    
You're very welcome.
Thanks for accepting this answer.
Good luck, call again.
--SA
Albin Abel 16-May-11 6:34am    
My 5
Sergey Alexandrovich Kryukov 16-May-11 6:43am    
Thank you, Albin.
--SA
C#
private static bool Findlogic(string item)
{
 if(item == "ABC" || item == "BBC")
    return true;
 else
    return false
}


then add you code like
C#
int i = AllRanks.FindIndex(Findlogic);


"i" will give you desired index.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 16-May-11 5:39am    
Correct, but... I voted 3 for quite ridiculous "if".
Should be: "return item == "ABC" || item == "BBC";" (!)
(I also fixed your formatting and added missing ";")
--SA
prathameshpitale 16-May-11 5:40am    
Hey thanks. but can you explain me this ?
Albin Abel 16-May-11 6:34am    
My 5
How come you did not see it in System.Collections.Generic.List?
Look:
http://msdn.microsoft.com/en-us/library/6sh2ey19(v=VS.100).aspx[^].

You will find a lot of methods including ready-to-use IndexOf (three overloads).

Ahh— predicate… sorry, now I see.

What's the problem about the code sample here:
http://msdn.microsoft.com/en-us/library/x1xzf2ca.aspx[^]?

—SA
 
Share this answer
 
Comments
prathameshpitale 16-May-11 5:20am    
I Saw the links before Questioning on this forum.. I have mentioned there i am not able to understand the given methods in example...

Can you help me understand the codE?
Sergey Alexandrovich Kryukov 16-May-11 5:36am    
How can I help you? By writing another piece of code? You won't understand it either.
(However, see the sample by Debojyoti Majumder. Any better?)
Maybe you need to learn about 1) generics, 2) delegates, looks at more simple examples first?
--SA
prathameshpitale 16-May-11 6:14am    
Thanx!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900