In array?

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

I can't find any pr-defined function for finding if a element is in a
array.
I write a function:


public static bool InArray(object[] myArray, object myObject)
{ foreach (object aObject in myArray)
{
if (aObject.ToString() == myObject.ToString())
return true;
}
return false;
}

When I call it with string array , it is OK like
string[] sMyArray ={ "a1", "a2", "a3" };
if (WillUtil.InArray(sMyArray ,"a2"))
......

But when I call it with int array, it fail with error message:
cannot convert from 'int[]' to 'object[]' like
int[] myIntArray={1, 3, 56};
if (WillUtil.InArray(myIntArray, 3))
......

Why string array can convert to object array, but int array can't?

How can I make a global function both for int and string array?
 
Hello,
Please see the MSDN for Array class. In Explicit Interface
Implementation sections it says that you can use Contains method of
IList interface. Just like following code snippet.

string[] stringArray = new string[]{"maqsood","ahmed","pakistan"};
if(((IList)stringArray).Contains("maqsood"))
return true;
else
return false;

HTH. Cheers
Maqsood Ahmed [MCP C#,SQL Server]
Kolachi Advanced Technologies
http://www.kolachi.net
 
Maqsood Ahmed said:
Hello,
Please see the MSDN for Array class. In Explicit Interface
Implementation sections it says that you can use Contains method of
IList interface.

You can also use the

Array.IndexOf(myArray, item)
 
Back
Top