版权声明:本文为 ls9512 原创文章,转载请注明出处! https://blog.csdn.net/ls9512/article/details/80280610
扩展方法系列
C# 扩展方法简介
C# 扩展方法01 —— 扩展 String & StringBuidler
C# 扩展方法02 —— 扩展Byte
扩展 IList 接口的意义
IList 泛型接口是 ICollection 泛型接口的子代,并且是所有泛型列表的基接口。List 作为业务编写中最常用的数据类型之一,有很多常用的功能并没有被原生实现,因此有必要做一些扩展,但同时为了提高泛用型,改为对其基接口进行扩展,使所有列表类型都可以获得这些扩展功能。
Get && Add 存取扩展
- 快速添加元素,并且防止重复
public static bool AddNotRepeat<T>(this IList<T> list, T item) {
if (!list.Contains(item))
{
list.Add(item);
return true;
}
return false;
}
- 尝试从列表中获取值,不存在返回默认值
public static T TryGetValue<T>(this IList<T> list, T value)
{
var index = list.IndexOf(value);
return index < 0 ? default(T) : value;
}
- 获取值的同时移除,不存在返回默认值
public static T GetAndRemove<T>(this IList<T> list, T value)
{
var ret = TryGetValue(list, value);
if (ret != null) list.Remove(ret);
return ret;
}
- 根据索引获取的同时移除
public static T GetAndRemove<T>(this IList<T> list, int index)
{
if (index > list.Count - 1) return default(T);
var result = list[index];
list.Remove(result);
return result;
}
- 获取第一个元素
public static T First<T>(this IList<T> list) {
return list.IsEmpty() ? default(T) : list[0];
}
- 获取最后一个元素
public static T Last<T>(this IList<T> list)
{
return list.IsEmpty() ? default(T) : list[list.Count - 1];
}
- 获取某元素的前一个元素
该接口建议只使用在不包含重复元素的列表中
public static T Before<T>(this IList<T> list, T item)
{
var index = list.IndexOf(item);
return index < 1 ? default(T) : list[index - 1];
}
- 获取某元素的后一个元素
该接口建议只使用在不包含重复元素的列表中
public static T After<T>(this IList<T> list, T item)
{
var index = list.IndexOf(item);
return index > list.Count - 2 ? default(T) : list[index + 1];
}
- 获取随机元素
该接口如需频繁调用,其中的Random建议静态存储,以减少new Random的开销
public static T Random<T>(this IList<T> list)
{
return list.Count > 0 ? list[new Random.Next(0, list.Count)] : default(T);
}
Sort 排序扩展
- 随机乱序
通过随机选取元素移动到列表末端一定次数,实现列表乱序,待改进
public static IList<T> RandSort<T>(this IList<T> list)
{
var rand = new Random();
var count = list.Count*2;
for (var i = 0; i < count; i++)
{
var randomNum = rand.Next(0, list.Count);
var item = list[randomNum];
list.Remove(item);
list.Add(item);
}
return list;
}
Move up & down 移动扩展
- 上移元素
该接口建议只使用在不包含重复元素的列表中
public static bool MoveUp<T>(this IList<T> list, T item, int step = 1) {
if (list == null || !list.Contains(item) || step < 1) return false;
var index = list.IndexOf(item);
if (index <= step - 1) return false;
list.Remove(item);
list.Insert(index - step, item);
return true;
}
- 下移元素
该接口建议只使用在不包含重复元素的列表中
public static bool MoveDown<T>(this IList<T> list, T item, int step = 1) {
if (list == null || !list.Contains(item) || step < 1) return false;
var index = list.IndexOf(item);
if (index >= list.Count - step) return false;
list.Remove(item);
list.Insert(index + step, item);
return true;
}