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

1 comment:

Anonymous said...

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