internal class MyList<T>
{
//储存数据
public T[] date = new T[0];
//记录个数
public int count = 0;
//定义一个属性来访问容量
public int Capcity
{
get { return date.Length; }
}
public int Count
{
get { return count; }
}
#region 定义添加的方法
public void Add(T item)
{
//判断长度是否为0 如果为0创建新的数组 将长度改为4
if (date.Length==0)
{
date = new T[4];
}
//判断数组是否满了
if (count==date.Length)
{
//扩容 重新创建了新数组(长度达到最高时)
T[] temp = new T[count*2];
//旧数组放到新数组里
for (int i = 0;i <date.Length; i++)
{
temp[i] = date[i];
}
date = temp;
}
date[count] = item;
count++;
}
#endregion
#region 插入数据的方法
/// <summary>
/// 插入数据的方法
/// </summary>
/// <param name="index">要插入的位置(索引)</param>
/// <param name="item">要插入的数据</param>
public void Insert(int index, T item)
{
//判断索引是否正确
if (index < 0 || index >= count)
{
//throw 抛出异常
throw new IndexOutOfRangeException("输入的索引不正确");
}
//插入数据时可能会出现超出长度 扩容
KR();
// 插入数据 index这个位置 后面的数据都要往后移
// 10
// 5 9
// 10 = 9 9 = 8 8 = 7 7=6 6= 5 4 9 8 7 6 5 4
for (int i = count - 1; i > index - 1; i--)
{
date[i + 1] = date[i];
}
//插入
date[index] = item;
count++;
}
#endregion
#region 查找数据的索引
public int IndexOf(T item)
{
for (int i = 0; i < count; i++)
{
if (Equals(date[i], item))
{
return i;
}
}
return -1;
}
#endregion
#region 索引器
public T this[int index]
{
get
{
if (index < 0 || index >= count)
{
throw new IndexOutOfRangeException("超出数组索引界限");
}
return date[index];
}
set
{
if (index < 0 || index >= count)
{
throw new IndexOutOfRangeException("超出数组索引界限");
}
date[index] = value;
}
}
#endregion
#region 扩容
private void KR()
{
if (date.Length == 0)
{
date = new T[4];
}
//判断数组是否满了
if (count == date.Length)
{
//扩容 重新创建了新数组(长度达到最高时)
T[] temp = new T[count * 2];
//旧数组放到新数组里
for (int i = 0; i < date.Length; i++)
{
temp[i] = date[i];
}
date = temp;
}
}
#endregion
#region 清空列表
public void Clear()
{
Array.Clear(date, 0, count);
count = 0;
}
#endregion
#region 排序
public void Sort()
{
Array.Sort(date, 0, count);
}
#endregion
#region 将列表转化为数组
public T[] ToArray()
{
T[] array = new T[count];
Array.Copy(date, array, count);
return array;
}
#endregion
#region 删除指定数据
public bool Remove(T item)
{
int index = IndexOf(item);
int i = 0;
if (index == -1)
{
return false;
}
RemoveAt(date[i]);
return true;
}
#endregion
#region 移除指定范围的数据
public int RemoveAt(T item)
{
int removecount = 0;
int i = 0;
while (i< count)
{
if (Equals(date[i], item))
{
RemoveAt(date[i]);
removecount++;
}
else
{
i++;
}
}
return removecount;
}
#endregion
}
4407

被折叠的 条评论
为什么被折叠?



