Tuesday, August 16, 2011

String Array Contains method does not work

 

I was trying to find out an elegant way to find whether an item exists in an array elements and found the contains method. But, for some reason it was not working directly the string[]strArr.Contains(item) for me. Tried in one windows application and it worked L, more confused, I started to figure out why?  I was wondering why the Contains method is not working and got the below solution. The idea is somewhat to achieve the below example

 

string[] ItemColletion = ....;
if (ItemColletion.Contains(“item”
))
{
    ...
}

In .NET 3.5 this is possible out of the box (make sure you reference System.Core and include the System.Linq namespace) but if you try to run this code in .NET 2.0 or .NET 3.0 you will get errors.

'System.Array' does not contain a definition for 'Contains' and no extension method 'Contains' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

Nevertheless the .NET Framework 2.0 does provide a Contains() method on any Array object. In the .NET Framework 2.0, System.Array implements the System.Collections.Generic.IList<T> interface. Unfortunately the implementation of the IList interface is provided at runtime so we do not see the methods in Visual Studio and we cannot write array.Contains(). Instead we have to cast the array to the appropriate IList interface before we can use the Contains method. See below an example:

 

string[] ItemCollection = new string[] {“Blue”,“Red”,“Green”};
if (!((IList<string>)ItemCollection).Contains(“Green”))
{
  
//Do something .....

}


 

MSDN Explanation:

http://msdn.microsoft.com/en-us/library/system.array(v=vs.80).aspx

clip_image001[4]Important:

In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

 

So you can now save yourself from looping thru the array to find an item. Rather use the Contains method and let framework work for you. J

Thanks for reading, If you have a more elegant solution – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

Array Contains method does not work

No comments:

Post a Comment