Prev | Current Page 293 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

The Predicate delegate type we??™ve used so far
isn??™t used very widely in .NET 2.0, but it becomes important in .NET 3.5 where it??™s a key
part of LINQ. Another useful delegate type with a return value is Comparison,
which can be used when sorting items. This works very well with anonymous methods.
Often you only need a particular sort order in one situation, so it makes sense to be
able to specify that order inline, rather than exposing it as a method within the rest of
the class. Listing 5.8 demonstrates this, printing out the files within the C:\ directory,
ordering them first by name and then (separately) by size.
static void SortAndShowFiles(string title,
Comparison sortOrder)
{
FileInfo[] files = new DirectoryInfo(@"C:\").GetFiles();
Array.Sort(files, sortOrder);
Console.WriteLine (title);
foreach (FileInfo file in files)
{
Console.WriteLine (" {0} ({1} bytes)",
file.Name, file.Length);
}
}
...
SortAndShowFiles("Sorted by name:",
delegate(FileInfo first, FileInfo second)
{ return first.Name.CompareTo(second.Name); }
);
SortAndShowFiles("Sorted by length:",
delegate(FileInfo first, FileInfo second)
{ return first.Length.CompareTo(second.Length); }
);
If we weren??™t using anonymous methods, we??™d have to have a separate method for
each of these sort orders. Instead, listing 5.8 makes it clear what we??™ll sort by in each
case right where we call SortAndShowFiles.


Pages:
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305