ForEach 的使用

ForEach 是一个循环结构,但是却不像 for 一样使用下标。

它用于 数组 和 集合 的遍历。

1、数组的遍历

int[] arr = new int[]{1, 2, 3, 4};
foreach(int element in arr)
{
     Console.WriteLine(element);
}

2、集合的遍历

using System.Collections;
...

ArrayList list = new ArrayList();
list.Add("hello");
list.Add("guys");

foreach(string e in list)
{
     Console.WriteLine(e);
}

3、泛型集合的遍历

using System.Collections.Generic;
...

List<int> list = new List<int>();
list.Add(1);
list.Add(3);
list.Add(5);

foreach(int e in list)
{
     Console.WriteLine(e);
}

 

注意:虽然,ForEach 和 For 一样都是循环结构,但是,它们之间比较大的区别就在于,在Foreach内部是不能对 元素进行修改的,否则会发生编译错误。

ForEach中的变量是ReadOnly变量。

foreach(int e in list)
{
     if(e == 3)
     {
           e = 6; //导致编译错误,不能修改,因为是 只读  变量 
     }
}


如果,想要对遍历 数组或集合中的数据进行修改的话,就 改用 for 循环吧!

 

有时,我们不仅希望能够在 数组 和集合中使用 Foreach 循环,我们还希望对我们自定义的类使用ForEach循环。

什么意思呢?就是,对自定义的类的使用 Foreach循环,获取内部的元素。

 

这时,对于自定义的类,需要去继承 IEnumerable 或者 IEnumerable<T> 接口,就可以了。

IEnumetable 接口中 只有一个方法IEnumerator GetEnumerator()

由于返回值为 IEnumerator 意味着,我们还需要去 定义一个类 继承IEnumerator 接口。

IEnumerator 是所有非泛型枚举数的基接口。枚举数可用于读取集合中的数据,但不能用于修改基础集合

在IEnumerator中,有三个东西 需要我们去实现,分别是 bool MoveNext(), void Reset(), object Current.

 

public class Person
    {
        string name;
        int age;

        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        public override string ToString()
        {
            return this.name + " " + this.age;
        }
    }

    public class People : IEnumerable
    {
        private Person[] people;

        public People(Person[] _people)
        {
            people = new Person[_people.Length];

            for (int i = 0; i < _people.Length; i++)
            {
                people[i] = _people[i];
            }
        }

        public IEnumerator GetEnumerator()
        {
            return (IEnumerator)new PeopleEnumerator(this);
        }

        public class PeopleEnumerator : IEnumerator
        {
            private People p;
            private int position = -1;

            public PeopleEnumerator(People p)
            {
                this.p = p;
            }

            public bool MoveNext()
            {
                if (position < p.people.Length - 1)
                {
                    position++;
                    return true;
                }
                else 
                {
                    return false;
                }
            }

            public void Reset()
            {
                position = -1;
            }

            public object Current
            {
                get { return this.p.people[position]; }
            }
        }

        static void Main()
        {
            Person[] Persons = new Person[] { new Person("kim", 20), new Person("tim", 23) };
            People p = new People(Persons);

            foreach (object obj in p) {
                Person o = (Person)obj;
                Console.WriteLine(o);
            }

            Console.ReadKey(true);
        }
    }

 

其实,我们不用实现 IEnumerable 接口也能够使用 Foreach循环。只要在 类中有 GetEnumerator()方法和一个具有

MoveNext()、Reset()、Current 这三个东西的类,同样能够能行!

代码示例:

public class Person
    {
        string name;
        int age;

        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        public override string ToString()
        {
            return this.name + " " + this.age;
        }
    }

    public class People
    {
        private Person[] people;

        public People(Person[] _people)
        {
            people = new Person[_people.Length];

            for (int i = 0; i < _people.Length; i++)
            {
                people[i] = _people[i];
            }
        }

        public PeopleEnumerator GetEnumerator()
        {
            return new PeopleEnumerator(this);
        }

        public class PeopleEnumerator
        {
            private People p;
            private int position = -1;

            public PeopleEnumerator(People p)
            {
                this.p = p;
            }

            public bool MoveNext()
            {
                if (position < p.people.Length - 1)
                {
                    position++;
                    return true;
                }
                else 
                {
                    return false;
                }
            }

            public void Reset()
            {
                position = -1;
            }

            public Person Current
            {
                get { return this.p.people[position]; }
            }
        }

        static void Main()
        {
            Person[] Persons = new Person[] { new Person("kim", 20), new Person("tim", 23) };
            People p = new People(Persons);

            foreach (Person mate in p){
                Console.WriteLine(mate);
            }

            Console.ReadKey(true);
        }
    }

上例中,没有再继承 IEnumerable 接口,但是得到了相同的结果。但是书上说,这个还能够改进,两者同时使用。

但是,我不太懂它的含义就,暂且搁置!


在 MyBatis 中,`<foreach>` 标签是一个非常重要的动态 SQL 元素,主要用于处理集合或数组类型的参数,支持批量操作,如插入、更新和查询。它能够将集合中的元素遍历并生成对应的 SQL 语句片段,从而实现灵活的 SQL 拼接功能。 ### 基本语法 `<foreach>` 标签的基本语法如下: ```xml <foreach item="item" index="index" collection="collection" open="(" close=")" separator=","> <!-- 写入具体的 SQL 语句 --> </foreach> ``` - `item`:用于表示集合中每一个元素的变量名。 - `index`:用于表示当前元素的索引(可选)。 - `collection`:指定需要遍历的集合或数组的名称。 - `open`:指定遍历开始前添加的字符串。 - `close`:指定遍历结束后添加的字符串。 - `separator`:指定每个元素之间的分隔符。 ### 使用场景及示例 #### 1. 批量删除 当需要根据一个 ID 列表进行批量删除时,可以使用 `<foreach>` 标签来生成 `IN` 子句。例如: ```java public void delete(@Param("list") List<String> list); ``` 对应的 XML 配置如下: ```xml <delete id="delete" parameterType="java.util.List"> delete from account where id in ( <foreach collection="list" item="id" index="index" separator="," open="" close=""> #{id} </foreach> ) </delete> ``` 上述代码会生成类似 `DELETE FROM account WHERE id IN (1, 2, 3)` 的 SQL 语句 [^5]。 #### 2. 动态条件查询 在查询时,如果希望根据一组 ID 来筛选数据,可以结合 `<where>` 和 `<foreach>` 标签实现动态查询: ```xml <select id="foreach_test" parameterType="map" resultType="com.pojo.Blog"> select * from Blog <where> <foreach collection="ids" item="id" open="and (" separator="or" close=")"> id=#{id} </foreach> </where> </select> ``` 该查询会生成类似 `SELECT * FROM Blog WHERE id IN (1 OR id=2 OR id=3)` 的 SQL 语句 [^3]。 #### 3. 批量插入 在进行批量插入操作时,可以通过 `<foreach>` 遍历列表,并为每条记录生成对应的值部分: ```xml <insert id="batchInsert"> INSERT INTO users (name, email) VALUES <foreach collection="userList" item="user" separator=","> (#{user.name}, #{user.email}) </foreach> </insert> ``` 此配置会生成类似 `INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com'), ('Bob', 'bob@example.com')` 的 SQL 语句 [^2]。 #### 4. 处理 Map 类型参数 当传入的参数是 `Map` 类型时,可以使用 `<foreach>` 遍历其中的键值对。例如: ```xml <insert id="insertMultiple"> INSERT INTO orders (order_id, customer_name) VALUES <foreach collection="orderMap" item="entry" separator=","> (#{entry.key}, #{entry.value}) </foreach> </insert> ``` 这段代码假设 `orderMap` 是一个 `Map<Integer, String>`,并且会生成对应的插入语句 [^1]。 ### 注意事项 - 在使用 `<foreach>` 时,必须确保传入的集合不为空,否则可能导致 SQL 语法错误。 - 如果传入的是 `List` 或 `Map`,应正确指定 `collection` 属性的值。 - 可以通过 `@Param` 注解显式命名参数,避免因参数类型复杂而出现解析问题。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值