Silverlight 3: Array Helper

Here is the collection of Array-related functions that are missing in Silverlight. I will upload the sample file with Unit Test later. The Silverlight Unit Test Framework which is released in December is not upgraded with Silverlight 3 so I will wait for new version.

Please feel free to give any suggestion, feedback or report any bug that you are testing. I really appreciate for that. As of now, I really don’t like the idea of using try-catch in my code. I will change it to something else later.

Silverlight – Array.ConvertAll

This method is the equivalent function of System.Array.ConvertAll. It allows you to convert an array of one type to an array of another.


public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter) {
if (array == null)
throw new ArgumentException();

return (from item in array select converter(item)).ToArray();
}

Example:


float[] af = {27.8F, 32.62F,99.3F,147.273F,7.5F,1412.2F };

int[] ai = ArrayExtension.ConvertAll(af,new Converter<float, int>((f) => (int)f));

foreach (var i in ai) {
MessageBox.Show(i.ToString());
}

Silverlight – Array.Exist(T)

This method is the equivalent function of System.Array.Exist(T). It allows you to determine whether the specified array contains elements that match the conditions defined by the specified predicate.


public static bool Exists<T>(this T[] array,
Predicate<T> match) {
if (array == null)
throw new ArgumentException();

return array.Any(item => match(item));
}

Example:


string[] dinosaurs = { "Compsognathus",
"Amargasaurus",   "Oviraptor",      "Velociraptor",
"Deinonychus",    "Dilophosaurus",  "Gallimimus",
"Triceratops" };

MessageBox.Show(string.Format(
"\nArray.Exists(dinosaurs, EndsWithSaurus): {0}",
ArrayExtension.Exists(dinosaurs, (s) => {
if ((s.Length > 5) &amp;&amp; (s.Substring(s.Length - 6).ToLower() == "saurus")) {
return true;
}
else {
return false;
}
})
)
);

Silverlight – Array.Find(T)

This method is the equivalent function of System.Array.Find(T). It allows you to search for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Array.


public static T Find<T>(this T[]  array,
Predicate<T> match) {
if (array == null)
throw new ArgumentException();

return (from item in array where match(item) select item).FirstOrDefault();
}

Example:


Point[] points = { new Point(100, 200),
new Point(150, 250), new Point(250, 375),
new Point(275, 395), new Point(295, 450) };

Point first = ArrayExtension.Find(points, (p) => {
if (p.X * p.Y > 100000) {
return true;
}
else {
return false;
}
});

Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);

Silverlight – Array.FindAll(T)

This method is the equivalent function of System.Array.FindAll(T). It allows you to retrieve all the elements that match the conditions defined by the specified predicate.


public static T[] FindAll<T>(T[] array,
Predicate<T> match) {
if (array == null)
throw new ArgumentException();

return (from item in array where match(item) select item).ToArray();
}

Example:


string[] dinosaurs = { "Compsognathus",
"Amargasaurus",   "Oviraptor",      "Velociraptor",
"Deinonychus",    "Dilophosaurus",  "Gallimimus",
"Triceratops" };

string[] subArray =
ArrayExtension.FindAll(dinosaurs, (s) => {
if ((s.Length > 5) &amp;&amp;
(s.Substring(s.Length - 6).ToLower() == "saurus")) {
return true;
}
else {
return false;
}
});

foreach (string dinosaur in subArray) {
MessageBox.Show(dinosaur);
}

Silverlight – Array.FindIndex(T)

  • FindIndex(T)(T[], Predicate(T))
  • FindIndex(T)(T[], Int32, Predicate(T))
  • FindIndex(T)(T[], Int32, Int32, Predicate(T))

Silverlight – Array.FindIndex(T)(T[], Predicate(T))

This method is the equivalent function of System.Array.FindIndex(T)(T[], Predicate(T)). It allows you to search for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire Array.


public static int FindIndex<T>(T[] array, Predicate<T> match) {
if (array == null)
throw new ArgumentException();

try {
var v = array
.Select((item, index) => new { item = item, position = index })
.Where(x => match(x.item)).FirstOrDefault();
return v.position;
}
catch {
return -1;
}
}

Silverlight – Array.FindIndex(T)(T[], Int32, Predicate(T))

This method is the equivalent function of System.Array.FindIndex(T)(T[], Int32, Predicate(T)). It allows you to search for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the Array that extends from the specified index to the last element.


public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match) {

if (array == null)
throw new ArgumentException();

if (startIndex >= array.Count()) {
throw new ArgumentOutOfRangeException();
}

try {
var v = array
.Select((item, index) => new { item = item, position = index })
.Where((x, index) => match(x.item) &amp;&amp; (index >= startIndex)).FirstOrDefault();

return v.position;
}
catch {
return -1;
}
}

Silverlight – FindIndex(T)(T[], Int32, Int32, Predicate(T))

This method is the equivalent function of System.Array.FindIndex(T)(T[], Int32, Int32, Predicate(T)). It allows you to search for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the Array that starts at the specified index and contains the specified number of elements.


public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) {
if (array == null)
throw new ArgumentException();

if (startIndex >= array.Count()) {
throw new ArgumentOutOfRangeException();
}

if (startIndex < 0 || count < 0) {
throw new ArgumentOutOfRangeException();
}

try {
var v = array
.Where((obj, index) => (index >= startIndex) &amp;&amp; (index <= count))
.Select((item, index) => new { item = item, position = index })
.Where((x, index) => match(x.item) &amp;&amp; (index >= startIndex) &amp;&amp; (index <= count)).FirstOrDefault();

return v.position;
}
catch {
return -1;
}
}

Example:


public void TestFindIndex() {
string[] dinosaurs = { "Compsognathus",
"Amargasaurus",   "Oviraptor",      "Velociraptor",
"Deinonychus",    "Dilophosaurus",  "Gallimimus",
"Triceratops" };

//Result: Array.FindIndex(dinosaurs, EndsWithSaurus): 1
MessageBox.Show(string.Format(
"\nArray.FindLastIndex(dinosaurs, EndsWithSaurus): {0}",
ArrayExtension.FindIndex(dinosaurs, EndsWithSaurus))
);

//Result: Array.FindIndex(dinosaurs, 4, EndsWithSaurus): 5
MessageBox.Show(string.Format(
"\nArray.FindLastIndex(dinosaurs, 4, EndsWithSaurus): {0}",
ArrayExtension.FindIndex(dinosaurs, 4, EndsWithSaurus))
);

//Result: Array.FindIndex(dinosaurs, 4, 3, EndsWithSaurus): -1
MessageBox.Show(string.Format(
"\nArray.FindLastIndex(dinosaurs, 4, 3, EndsWithSaurus): {0}",
ArrayExtension.FindIndex(dinosaurs, 4, 3, EndsWithSaurus))
);
}
private static bool EndsWithSaurus(String s) {
if ((s.Length > 5) &amp;&amp;
(s.Substring(s.Length - 6).ToLower() == "saurus")) {
return true;
}
else {
return false;
}
}

Silverlight – Array.FindLast(T)

This method is the equivalent function of System.Array.FindLast(T). It allows you to search for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire Array.


public static T FindLast<T>(T[] array,Predicate<T> match) {
return array
.Last(item => match(item));
}

Example:


string[] dinosaurs = { "Compsognathus",
"Amargasaurus",   "Oviraptor",      "Velociraptor",
"Deinonychus",    "Dilophosaurus",  "Gallimimus",
"Triceratops" };

MessageBox.Show(string.Format(
"\nArray.FindLast(dinosaurs, EndsWithSaurus): {0}",
ArrayExtension.FindLast(dinosaurs, (s) => {
if ((s.Length > 5) &amp;&amp;
(s.Substring(s.Length - 6).ToLower() == "saurus")) {
return true;
}
else {
return false;
}
}))
);

Silverlight – Array.FindLastIndex

  • FindLastIndex(T)(T[], Predicate(T))
  • FindLastIndex(T)(T[], Int32, Predicate(T))
  • FindLastIndex(T)(T[], Int32, Int32, Predicate(T))

Silverlight – FindLastIndex(T)(T[], Predicate(T))

This method is the equivalent function of System.Array.FindLastIndex(T)(T[], Predicate(T)). It allows you to search for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire Array.


public static int FindLastIndex<T>(T[] array, Predicate<T> match) {
if (array == null)
throw new ArgumentException();
try {
var v = array
.Select((item, index) => new { item = item, position = index })
.Last(x => match(x.item));

return v.position;
}
catch (Exception e) {
return -1;
}
}

Silverlight – FindLastIndex(T)(T[], Int32, Predicate(T))

This method is the equivalent function of System.Array.FindLastIndex(T)(T[], Int32, Predicate(T)). It allows you to search for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the Array that extends from the first element to the specified index.


public static int FindLastIndex<T>(T[] array, int startIndex,  Predicate<T> match) {

if (array == null)
throw new ArgumentException();

if (startIndex >= array.Count()) {
throw new ArgumentOutOfRangeException();
}
try {
var v = array
.Where((obj, index) => index >= startIndex)
.Select((item, index) => new { item = item, position = index })
.Last(x => match(x.item));
return v.position;
}
catch (Exception e) {
return -1;
}
}

Silverlight – FindLastIndex(T)(T[], Int32, Int32, Predicate(T))

This method is the equivalent function of System.Array.FindLastIndex(T)(T[], Int32, Int32, Predicate(T)). It allows you to search for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the Array that contains the specified number of elements and ends at the specified index.


public static int FindLastIndex<T>(T[] array,int startIndex,int count,Predicate<T> match){

if (array == null)
throw new ArgumentException();

if (startIndex >= array.Count()) {
throw new ArgumentOutOfRangeException();
}

if (startIndex < 0 || count < 0) {
throw new ArgumentOutOfRangeException();
}

try {
var v = array
.Where((obj, index) => (index >= startIndex) &amp;&amp; (index <= count))
.Select((item, index) => new { item = item, position = index })
.Last(x => match(x.item));
return v.position;
}
catch (Exception e) {
return -1;
}
}

Example:


public void TestFindLastIndex() {
string[] dinosaurs = { "Compsognathus",
"Amargasaurus",   "Oviraptor",      "Velociraptor",
"Deinonychus",    "Dilophosaurus",  "Gallimimus",
"Triceratops" };

//Result: Array.FindLastIndex(dinosaurs, EndsWithSaurus): 5
MessageBox.Show( string.Format(
"\nArray.FindLastIndex(dinosaurs, EndsWithSaurus): {0}",
ArrayExtension.FindLastIndex(dinosaurs, EndsWithSaurus))
);

//Result: Array.FindLastIndex(dinosaurs, 4, EndsWithSaurus): 1
MessageBox.Show(string.Format(
"\nArray.FindLastIndex(dinosaurs, 4, EndsWithSaurus): {0}",
ArrayExtension.FindLastIndex(dinosaurs, 4, EndsWithSaurus))
);

//Result: Array.FindLastIndex(dinosaurs, 4, 3, EndsWithSaurus): -1
MessageBox.Show(string.Format(
"\nArray.FindLastIndex(dinosaurs, 4, 3, EndsWithSaurus): {0}",
ArrayExtension.FindLastIndex(dinosaurs, 4, 3, EndsWithSaurus))
);
}
private static bool EndsWithSaurus(String s) {
if ((s.Length > 5) &amp;&amp;
(s.Substring(s.Length - 6).ToLower() == "saurus")) {
return true;
}
else {
return false;
}
}

Silverlight – Array.TrueForAll(T)

This method is the equivalent function of System.Array.TrueForAll(T). It allows you to determine whether every element in the array matches the conditions defined by the specified predicate.


public static bool TrueForAll<T>(T[] array, Predicate<T> match) {
if (array == null)
throw new ArgumentException();

return array.Any( item => match(item));
}

Example:


private void TrueForAllTest() {
string[] dinosaurs = { "Compsognathus",
"Amargasaurus",   "Oviraptor",      "Velociraptor",
"Deinonychus",    "Dilophosaurus",  "Gallimimus",
"Triceratops" };

MessageBox.Show(string.Format(
"\nArray.TrueForAll(dinosaurs, EndsWithSaurus): {0}",
ArrayExtension.TrueForAll(dinosaurs, EndsWithSaurus))
);
}
private static bool EndsWithSaurus(String s) {
if ((s.Length > 5) &amp;&amp;
(s.Substring(s.Length - 6).ToLower() == "saurus")) {
return true;
}
else {
return false;
}
}

ArgumentOutOfRangeException

I’m using ArugmentOutOfRangeException in some of my code that I posted above. So, you may need to copy the following code when you are testing my codes.


public class ArgumentOutOfRangeException : SystemException {
public ArgumentOutOfRangeException(){}
public ArgumentOutOfRangeException(string message) { }
public ArgumentOutOfRangeException(string message, Exception innerException) { }
public ArgumentOutOfRangeException(string message, string paramName) { }
//public override string Message { get; }
}

Yes. That’s all. I found those functions very useful when you are doing Silverlight-port for the existing codes. As I mentioned before, please feel free to give any suggestion/feedback.  Thanks.

References ~

6 thoughts on “Silverlight 3: Array Helper

  1. cool :) but you seem to duplicate a fair bit of stuff thats already in (I)Enumerable :)

    the index functions are useful though :)

  2. I have problem using Array.Exists() code.

    Compiler claims that the System.Array does not have a method “Any”.
    (in return array.Any(item => match(item));)

    Could you help with that?

    I am using Silverlight 4 and .Net 4.

    Thanks in advance.

Leave a Reply

Your email address will not be published. Required fields are marked *