Friday, June 11, 2010

C#, searching for an element in a list

The List class is mighty powerful. It can make an arraylist out of any class. The problem is that it's not always easy finding some internal class value in an object in that list.

Say I have an alarm class:
public class Alarms
{
public DateTime time;
public enum alarmType { major, minor };
public string originator;
}
And a lot of these are encapsulated in a list:
List alarmList;
If a user is looking at this list (probably in a listview) and has modified a value of an individual alarm in the list, how do we find that alarm in the list? (In my program, it's a temporary buffer which multiple threads write to and from)

Simply put, we use delegates.

If the user has extracted an alarm from the list called "al" and modified the values, and then wants to put it back to a list that has probably been modified and has new index values, use this:
int indexToLookFor = alarmList.FindIndex(delegate(Alarms alarm)
{
return alarm.time == al.time && alarm.alarmType == al.alarmType && alarm.originator == al.originator;
});
if (indexToLookFor >= 0)
{
//the alarm has been looked at, make it a minor one
alarmList[indexToLookFor].alarmType = alarmType.minor;
}
It uses the FindIndex function of , comparing each variable of the class. Granted, you could write your own For loop to do it, but this is much quicker, and in my opinion, more grand.

No comments:

Post a Comment