Arraylist 小练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace sln0716
{
    class Program
    {
        static void Main(string[] args)
        {

//            案例:两个集合{ “a”,“b”,“c”,“d”,“e”}和{ “d”, “e”, “f”, “g”, “h” },把这两个集合去除重复项合并成一个

            //ArrayList al1 = new ArrayList() { "a","b","c","d","e"};
            //ArrayList al2 = new ArrayList() { "d", "e", "f", "g", "h"};
            //ArrayList al3 = new ArrayList();
            //al3.AddRange(al1);

            //for (int i = 0; i < al2.Count; i++)
            //{
            //    if (!al3.Contains(al2[i]))
            //    {
            //        al3.Add(al2[i]);
            //    }
            //}

            //foreach (object item in al3)
            //{
            //    Console.WriteLine(item);
            //}
            //案例:随机生成10个1-100之间的数放到ArrayList中,要求这10个数不能重复,并且都是偶数
            //ArrayList al = new ArrayList();
            //while (al.Count < 10)
            //{
            //    Random ran = new Random();
            //    int n = ran.Next(1, 101);
            //    if (n % 2 == 0)
            //    {
            //        //判断al中不包含n才添加
            //        if (!al.Contains(n))
            //        {
            //            al.Add(n);
            //        }
            //    }
            //}

            //foreach (object item in al)
            //{
            //    Console.WriteLine(item);
            //}
//练习:有一个字符串是用空格分隔的一系列整数,写一个程序把其中的整数做如下重新排列打印出来:奇数显示在左侧、偶数显示在右侧。比如‘2 7 8 3 22 9’显示成‘7 3 9 2 8 22

            string str = "2 7 8 3 22 9";
            //奇数
            ArrayList odds = new ArrayList();
            //偶数
            ArrayList evens = new ArrayList();
            string[] strArr = str.Split(' ');
            foreach (string item in strArr)
            {
                int n = int.Parse(item);
                if (n % 2 == 0)
                {
                    evens.Add(n);
                }
                else
                {
                    odds.Add(n);
                }
            }
            odds.AddRange(evens);


            string tmp = odds[0].ToString();
            for (int i = 1  ; i < odds.Count; i++)
            {
                tmp = tmp + " " + odds[i].ToString();
            }
            Console.WriteLine(tmp + "abc");

            Console.Read();
        }
    }
}

posted @ 2012-08-25 13:14  小薇林  阅读(304)  评论(0编辑  收藏  举报