zoukankan      html  css  js  c++  java
  • C# 中 foreach的用法 (补List 的 ForEach细节)

    foreach有点像是for的增强版

    在C#中有时候会遇到需要循环输出的情况,比如这样:

    using Syatem
    using System.Collections;
    using System.Collections.Generic;
    
    class one {
        int[] A = { 1, 2, 3, 4, 5 };
        void Main()
        {
         //for
    for (int i = 0; i < A.Length; i++) Console.WriteLine(A[i]);
         //foreach
    foreach (int i in A) Console.WriteLine(i); } }

    可以看出,当不需要麻烦的操作的时候,不需要针对第 i 元素进行奇怪的操作时,foreach提高了写代码的整洁和效率;


    注:

    1.foreach中的 i 就是A中的元素,如果A是字符串,则应该写为

    foreach (char i in A)
     Console.WriteLine(i);

    2.不要在foreach中试图增删,这样会报异常!需使用for!

    3.List中有一个ForEach,可以实现在循环内增删,关于此还有挺多可以说的:

      List中ForEach是有委托的:要对 Action<T> 的每个元素执行的 List<T> 委托

    标准写法: public void ForEach (Action<T> action); ,然后官方给出了一个示例,由此就可以看出用法了:

     1 using System;
     2 using System.Collections.Generic;
     3 
     4 class Program
     5 {
     6     static void Main()
     7     {
     8         List<String> names = new List<String>();
     9         names.Add("Bruce");
    10         names.Add("Alfred");
    11         names.Add("Tim");
    12         names.Add("Richard");
    13 
    14         // Display the contents of the list using the Print method.
    15         names.ForEach(Print);
    16 
    17         // The following demonstrates the anonymous method feature of C#
    18         // to display the contents of the list to the console.
    19         names.ForEach(delegate(String name)
    20         {
    21             Console.WriteLine(name);
    22         });
    23     }
    24 
    25     private static void Print(string s)
    26     {
    27         Console.WriteLine(s);
    28     }
    29 }
    30 /* This code will produce output similar to the following:
    31  * Bruce
    32  * Alfred
    33  * Tim
    34  * Richard
    35  * Bruce
    36  * Alfred
    37  * Tim
    38  * Richard
    39  */
    点击查看全部示范代码

    by the way,此操作是O(n)操作。

  • 相关阅读:
    Wide & Deep Learning for Recommender Systems
    两个经典问题
    Vlog简介
    中文dumps显示
    用Python提取中文关键词
    【STL】算法 — partial_sort
    c字符串分割 strtok()
    JSP的声明(statement)
    layui之ajax巨坑
    jQuery 库中的 $() 是什么?(答案如下)
  • 原文地址:https://www.cnblogs.com/wayne-tao/p/11313670.html
Copyright © 2011-2022 走看看