Here are the details on the Generic find and a Sort thrown in for good measure. The sample Team class to follow at the end.
This is a sample of the anonymous method used for the find predicate and the sort as well.
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
List teams = new List();
Team canadiens = new Team("Montreal Canadiens", "Habs", 1);
teams.Add(canadiens);
Team senators = new Team("Ottawa Senators", "Sens", 99);
teams.Add(senators);
Team sabres = new Team("Buffalo Sabres", "Sabres", 5);
teams.Add(sabres);
Team leafs = new Team("Toronto Maple Leafs", "Leafs", 75);
teams.Add(leafs);
Team bruins = new Team("Boston Bruins", "Bruins", 5);
teams.Add(bruins);
Console.WriteLine(Environment.NewLine + "Teams as added to the List");
foreach (Team team in teams)
{
Console.WriteLine("Team Name = " + team.TeamName + " (" + team.Nickname + ")");
}
Console.WriteLine(Environment.NewLine);
Team myFavourite = teams.Find(delegate(Team team)
{
return (String.Compare(team.Nickname, "HABS", true) == 0);
});
Console.WriteLine("My favourite team is the " + myFavourite.TeamName);
Console.WriteLine(Environment.NewLine + "\t\tGO " + myFavourite.Nickname + " GO!");
Console.WriteLine(Environment.NewLine + "Order the teams by default sort order");
teams.Sort();
foreach (Team team in teams)
{
Console.WriteLine(team.Rating + ") " + team.Nickname);
}
teams.Sort(TeamSortByRating);
Console.WriteLine(Environment.NewLine + "Order the teams by rating");
foreach (Team team in teams)
{
Console.WriteLine(team.Rating + ") " + team.Nickname);
}
Console.ReadLine();
}
public static int TeamSortByRating(Team team1, Team team2)
{
if (team1.Rating == team2.Rating)
{
return team1.TeamName.CompareTo(team2.TeamName);
}
else
{
return team1.Rating.CompareTo(team2.Rating);
}
}
}
}
namespace TestConsole
{
public class Team : IComparable
{
public string TeamName
{
get;
set;
}
public string Nickname
{
get;
set;
}
public int Rating
{
get;
set;
}
public Team(string teamName, string nickname, int rating)
{
TeamName = teamName;
Nickname = nickname;
Rating = rating;
}
#region IComparable Members
public int CompareTo(object obj)
{
return this.TeamName.CompareTo(((Team)obj).TeamName);
}
#endregion
}
}