Mittwoch, 27. Februar 2008

Dot Net (C#): List.ForEach() Methode

Verwenden der ForEach()-Methode einer Generic-List:

static void Main()
{
List<String> names = new List<String>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");

// Display the contents of the list using the Print method.
names.ForEach(Print);

// The following demonstrates the anonymous method feature of C#
// to display the contents of the list to the console.
names.ForEach(delegate(String name)
{
Console.WriteLine(name);
});
}

private static void Print(string s)
{
Console.WriteLine(s);
}


Generisch als Erweiterungsmethode für IEnumerable:
public static class IEnumerableExtension
{
public static void PrintItem<T>(this T item)
{
Console.WriteLine(item.ToString());
}

public static void PrintAllItems<T>(this IEnumerable<T> enumerable)
{
foreach (T item in enumerable)
{
PrintItem(item);
}
}
}

3 Kommentare:

Kirill Osenkov hat gesagt…

Klasse!

Kannst Du auch so eine ForEach Methode fuer beliebige IEnumerable<T> implementieren?? ;-)

Kirill Osenkov hat gesagt…

Tipp: extension methods

Mario Schneider hat gesagt…

Ich habs mal versucht, weiß nicht, ob du das meinst ;)