Generic List ForEach() Method
.Net framework generic list ForEach() method allow us to perform the specified action on each element of the List<T>. the ForEach()
method exists in under System.Collections.Generic namespace. this method need to pass a parameter named 'action'. this 'action'
parameter type is System.Action<T>. the Action<T> delegate to perform on each element of the List<T>.
if the parameter 'action' is null the method throw an exception named ArgumentNullException. in the bellow example we created a String type generic list. by using the ForEach() method we insert a * character at the beginning of each element of generic list.
the following asp.net c# example code demonstrate us how can we perform a specified action on each element of a generic list in an asp.net application.
if the parameter 'action' is null the method throw an exception named ArgumentNullException. in the bellow example we created a String type generic list. by using the ForEach() method we insert a * character at the beginning of each element of generic list.
the following asp.net c# example code demonstrate us how can we perform a specified action on each element of a generic list in an asp.net application.
GenericListForEachMethod.aspx
<%@ Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
List<string> colors = new List<string>() {"Lavender","LawnGreen","SeaGreen"};
colors.Add("LightGoldenRodYellow");
colors.Add("ForestGreen");
Label1.Text = "List Elements....<br />";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "<br /><br />After Call ForEach() Method List Elements are.....<br />";
colors.ForEach(delegate (String s)
{
Label1.Text +="<br />" + s.ToLower().Insert(0,"*");
});
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Generic List ForEach() - How to perform the specified action on each element of the List</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Olive; font-style:italic;">
System.Collections.Generic.List ForEach() Method
<br /> How to perform the specified action on each element of the List
</h2>
<hr width="575" align="left" color="ForestGreen" />
<asp:Label
ID="Label1"
runat="server"
ForeColor="DarkOrchid"
Font-Size="Large"
Font-Names="Courier New"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Generic List ForEach() Method"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>
