Thursday, March 13, 2008

Array.FindIndex

To find index of a element in array often we use statement for by next way:

static int SearchIndexOfItemInArray_via_for(int[] data, int foundItemValue)
{
int itemIndex = -1;
for (int i = 0; i < data.Length; i++)
{
if (foundItemValue == data[i])
{
itemIndex = i;
break;
}
}
return itemIndex;
}
C# (2.0) suggests another way to search index of element with help of method Array.FindIndex and delegate:

static int SearchIndexOfItemInArray_via_FindIndex(int[] data, int foundItemValue)
{
return Array.FindIndex(data, delegate(int item)
{
return item == foundItemValue;
});
}
Additional links:

Array..::.FindIndex<(Of <(T>)>) Generic Method (array<T>[]()[], Predicate<(Of <(T>)>))

Predicate<(Of <(T>)>) Generic Delegate

2 comments:

Anonymous said...

Nice example and counter-example. Much easier to follow than say, the MSDN page.

simi said...

hi,

First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

There is a good C# resource site, Have alook

http://www.csharptalk.com/2009/09/c-array.html
http://www.csharptalk.com/2009/10/creating-arrays.html

simi