---------------------- ASP.Net+Android+IO开发S、.Net培训、期待与您交流! ----------------------
泛型集合
概念:就是只能存储特定类型的集合集合跟数组本质的区别:
数组的长度一旦声明了 就不能再改变了
而集合可以任意更改长度
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _02泛型集合
{
class Program
{
static void Main(string[] args)
{
创建了一个泛型集合对象 只能存储int类型
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
int[] nums = { 4, 5, 6, 7, 8, 9 };
list.AddRange(nums);
// list.Remove(1); 根据集合中的值去删除
foreach (var item in list)
{
Console.WriteLine(item);
}
Console.ReadKey();
使用List泛型集合分拣奇偶数
求奇数集合的最大值、最小值、平均值、和
偶数 同上
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> oddList = new List<int>(); //存放奇数的集合
List<int> evenList = new List<int>();//存放偶数的集合
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] % 2 == 0)
{
evenList.Add(nums[i]);
}
else
{
oddList.Add(nums[i]);
}
}
int oddMax =oddList[0];
int oddMin = oddList[0];
int oddSum = 0;
for (int i = 0; i < oddList.Count; i++)
{
if (oddList[i] > oddMax)
{
oddMax = oddList[i];
}
if (oddList[i] < oddMin)
{
oddMin = oddList[i];
}
oddSum += oddList[i];
}
Console.WriteLine("这个奇数集合的最大值是{0},最小值是{1},平均值是{2},总和是{3}",oddMax,oddMin,oddSum/oddList.Count,oddSum);
int evenMax = evenList[0];
int evenMin = evenList[0];
int evenSum = 0;
for (int i = 0; i < evenList.Count; i++)
{
if (evenList[i] > evenMax)
{
evenMax = evenList[i];
}
if (evenList[i] < evenMin)
{
evenMin = evenList[i];
}
evenSum += evenList[i];
}
Console.WriteLine("这个偶数集合的最大值是{0},最小值是{1},平均值是{2},总和是{3}",evenMax,evenMin,evenSum/evenList.Count,evenSum);
Console.ReadKey();
}
}
}
---------------------- ASP.Net+Android+IO开发S、.Net培训、期待与您交流! ----------------------