调整数据列表内的顺序,现写成扩展方法工具类
public static class CollectionHelper
{
//交换List项的顺序
public static bool ExchangeOrder(this IList list, int sourceID, int newID)
{
if (sourceID >= list.Count || sourceID < 0 || newID >= list.Count || newID < 0 || sourceID == newID) return false;
try
{
var temp = list[sourceID];
list[sourceID] = list[newID];
list[newID] = temp;
return true;
}
catch (Exception)
{
return false;
}
}
///
/// 向上移动
///
///
/// The 数据列表 list
/// The 需要移动的id
/// The 移动的 位数. 默认为1, 几位就向上移动几位
///
public static bool MoveUpper(this IList list, int id, int num = 1)
{
return list.MoveItem(id, id - num);
}
//向下移动
public static bool MoveDown(this IList list, int id, int num = 1)
{
return list.MoveItem(id, id + num);
}
//移动到顶部
public static bool MoveTopper(this IList list, int id)
{
return list.MoveItem(id, 0);
}
//移动到底部
public static bool MoveBottom(this IList list, int id)
{
return list.MoveItem(id, list.Count -1);
}
///
/// 移动
///
///
/// 数据列表
/// 原来的数据ID
/// 移动后数据ID
///
public static bool MoveItem(this IList list, int sourceID, int newID)
{
if (sourceID >= list.Count || sourceID < 0 || newID >= list.Count || newID < 0 || sourceID == newID) return false;
try
{
var temp = list[sourceID];
list.RemoveAt(sourceID);
list.Insert(newID, temp);
return true;
}
catch (Exception)
{
return false;
}
}
}
调用的方法:
class CollectionSample
{
public void Test()
{
List stuList = new List();
Student stu = new Student(1, "zhangSan");
stuList.Add(stu);
stu = new Student(2, "LiSi");
stuList.Add(stu);
stu = new Student(3, "WangWu");
stuList.Add(stu);
stu = new Student(4, "ZhangLiu");
stuList.Add(stu);
string msg = string.Empty;
foreach (Student item in stuList)
{
msg += String.Format("ID: {0}, Name: {1} ", item.id, item.name);
}
//Exchange(stuList);
Move(stuList);
}
private static void Exchange(List stuList)
{
CollectionHelper.ExchangeOrder(stuList, 2, 1);
string newMsg = string.Empty;
foreach (Student item in stuList)
{
newMsg += String.Format("ID: {0}, Name: {1} ", item.id, item.name);
}
}
private static void Move(List stuList)
{
CollectionHelper.MoveUpper(stuList, 2, 3);
string newMsg = string.Empty;
foreach (Student item in stuList)
{
newMsg += String.Format("ID: {0}, Name: {1} ", item.id, item.name);
}
}
}