First, I know there are methods off of the generic List<>
class already in the framework do iterate over the List<>
.
But as an
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
action(item);
}
... and call it thusly:
Each(myList, i => Console.WriteLine(i));
public static void Each<T>(this IEnumerable<T> items, Action<T> action) {
foreach (var item in items) {
action(item);
} }
... and call it thusly:
myList.Each(x => { x.Enabled = false; });
Want to put out there that there is not much to worry about if someone provides an answer as an extension method because an extension method is just a cool way to call an instance method. I understand that you want the answer without using an extension method. Regardless if the method is defined as static, instance or extension - the result is the same.
The code below uses the code from the accepted answer to define an extension method and an instance method and creates a unit test to show the output is the same.
public static class Extensions
{
public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
}
[TestFixture]
public class ForEachTests
{
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
private string _extensionOutput;
private void SaveExtensionOutput(string value)
{
_extensionOutput += value;
}
private string _instanceOutput;
private void SaveInstanceOutput(string value)
{
_instanceOutput += value;
}
[Test]
public void Test1()
{
string[] teams = new string[] {"cowboys", "falcons", "browns", "chargers", "rams", "seahawks", "lions", "heat", "blackhawks", "penguins", "pirates"};
Each(teams, SaveInstanceOutput);
teams.Each(SaveExtensionOutput);
Assert.AreEqual(_extensionOutput, _instanceOutput);
}
}
Quite literally, the only thing you need to do to convert an extension method to an instance method is remove the static
modifier and the first parameter of the method.
This method
public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
becomes
public void Each<T>(Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
You can traverse each string in the list and even you can search in the whole generic using a single statement this makes searching easier.
public static void main(string[] args)
{
List names = new List();
names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);
string stringResult = names.Find( name => name.Equals(“Garima”));
}
Is this what you're asking for?
int[] numbers = { 1, 2, 3 };
numbers.ToList().ForEach(n => Console.WriteLine(n));
The above could also be written with less code as:
new List<SomeType>(items).ForEach(
i => Console.WriteLine(i)
);
This creates a generic list and populates it with the IEnumerable and then calls the list objects ForEach.