- public class HomeController : Controller
- {
- // GET: Home
- public ActionResult Index()
- {
- //return new NotFoundResult();
- return View();
- }
- public ActionResult Error()
- {
- return View();
- }
- public ActionResult Test()
- {
- List<T1> list = new List<T1>() {
- new T1() { id=1,name="张山"},
- new T1() { id=2,name="张山"},
- new T1() { id=1,name="张山"},
- new T1() { id=2,name="张山"},
- new T1() { id=2,name="张山"},
- };
- return Json(list, JsonRequestBehavior.AllowGet);
- }
- public ActionResult Test1()
- {
- List<T1> list = new List<T1>() {
- new T1() { id=1,name="张山"},
- new T1() { id=2,name="张山"},
- new T1() { id=1,name="张山"},
- new T1() { id=2,name="张山"},
- new T1() { id=2,name="张山"},
- };
- List<T1> list2 = new List<T1>();
- list.ForEach(m => list2.Add(m));
- return Json(list2, JsonRequestBehavior.AllowGet);
- }
- private void Th(T1 t)
- {
- }
- }
- public class T1
- {
- public int id { get; set; }
- public string name { get; set; }
- }
复制代码
自己随便写的,我感觉,一般循环做什么事情的时候用这个玩意比较好。
下面是微软给的代码:
- 所需的主题如下所示。但此主题未包含在此库中。
- List<T>.ForEach 方法
- 其他版本
- 2013/12/13
- 对 List<T> 的每个元素执行指定操作。
- Namespace: System.Collections.Generic
- 程序集: mscorlib(位于 mscorlib.dll 中)
- 语法
- C#VB
- public void ForEach(
- Action<T> action
- )
- 参数
- action
- 类型: System.Action<T>
- 要对 List<T> 的每个元素执行的 Action<T> 委托。
- 例外
- 异常 条件
- ArgumentNullException
- action 为 null。
- 备注
- Action<T> 是对方法的委托,它对传递给自己的对象执行操作。当前 List<T> 的元素被分别传递给 Action<T> 委托。
- 此方法的运算复杂度为 O(n),其中 n 是 Count。
- 示例
- 下面的示例演示如何使用 Action<T> 委托来打印 List<T> 对象的内容。在此示例中,Print 方法用于将列表的内容显示到控制台。
- 说明注意:
- 除了使用 Print 方法显示内容外,该 C# 示例还演示了如何使用匿名方法将结果显示到控制台。
- C#VB
- using System;
- using System.Collections.Generic;
- class Example
- {
- private static System.Windows.Controls.TextBlock outputBlock;
- public static void Demo(System.Windows.Controls.TextBlock outputBlock)
- {
- Example.outputBlock = outputBlock;
- 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.
- names.ForEach(delegate(String name)
- {
- outputBlock.Text += name + "\n";
- });
- }
- private static void Print(string s)
- {
- outputBlock.Text += s + "\n";
- }
- }
- /* This code will produce output similar to the following:
- * Bruce
- * Alfred
- * Tim
- * Richard
- * Bruce
- * Alfred
- * Tim
- * Richard
- */
复制代码
|