I have an array of classes. Each class contains two values (UserName, and UserID).
I need to search the array such as "give my the ID for username Bob Smith."
Other than looping through each value in the array, is there another way I can search it such as searcharray(username, "Bob Smith")?
chrisPosted Oct 3, 2007, 10:50 AM
AlanPosted Oct 3, 2007, 10:41 AM
If you're using .NET 2.0 or greater, you can do it after a fashion with code like this:
using System;
class Test
{
static string matchUserName;
static void Main()
{
MyClass[] myArray = new MyClass[3];
myArray[0] = new MyClass("Fred Bloggs", 12);
myArray[1] = new MyClass("Bob Smith", 25);
myArray[2] = new MyClass("Jack Jones", 42);
matchUserName = "Bob Smith";
MyClass mc = Array.Find(myArray, MatchesUserName);
if (mc != null)
{
Console.WriteLine("The UserId for {0} is {1}", matchUserName, mc.UserId);
}
else
{
Console.WriteLine("{0} is not in the array", matchUserName);
}
Console.ReadKey();
}
private static bool MatchesUserName(MyClass mc)
{
if (mc.UserName == matchUserName)
{
return true;
}
return false;
}
}
class MyClass
{
private string userName;
private int userId;
public string UserName
{
get {return userName;}
}
public int UserId
{
get {return userId;}
}
public MyClass (string userName, int userId)
{
this.userName = userName;
this.userId = userId;
}
}