C#List<T> 扩展方法
using System;
using System.Collections.Generic;
using System.Linq;
namespace ListExtDemo
{
// 集合扩展静态类
public static class ListExtensions
{
public static bool IsNullOrEmpty<T>(this List<T> source)
{
return source == null || source.Count == 0;
}
public static List<T> DistinctSelf<T>(this List<T> source)
{
return source.IsNullOrEmpty() ? new List<T>() : source.Distinct().ToList();
}
public static List<T> Page<T>(this List<T> source, int pageIndex, int pageSize)
{
if (source.IsNullOrEmpty() || pageIndex < 1 || pageSize < 1)
return new List<T>();
return source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
public static decimal GetSum<T>(this List<T> source, Func<T, decimal> selector)
{
return source.IsNullOrEmpty() ? 0m : source.Sum(selector);
}
public static Dictionary<TKey, TValue> ToMap<T, TKey, TValue>(
this List<T> source, Func<T, TKey> keyFunc, Func<T, TValue> valFunc)
{
return source.IsNullOrEmpty()
? new Dictionary<TKey, TValue>()
: source.ToDictionary(keyFunc, valFunc);
}
}
// 测试实体类
public class Goods
{
public int Id { get; set; }
public string GoodsName { get; set; }
public decimal Price { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<int> numList = new List<int> { 2, 5, 2, 8, 5, 9 };
Console.WriteLine("====数值集合测试====");
Console.WriteLine($"集合是否为空:{numList.IsNullOrEmpty()}");
var distinctNum = numList.DistinctSelf();
Console.Write("去重后数据:");
distinctNum.ForEach(x => Console.Write($"{x} "));
Console.WriteLine();
List<Goods> goodsList = new List<Goods>
{
new Goods{Id=1,GoodsName="矿泉水",Price=2.5m},
new Goods{Id=2,GoodsName="面包",Price=6.8m},
new Goods{Id=3,GoodsName="牛奶",Price=4.2m},
new Goods{Id=4,GoodsName="饼干",Price=8.9m}
};
Console.WriteLine("\n====实体集合测试====");
var pageData = goodsList.Page(2, 2);
Console.WriteLine("第二页分页数据:");
foreach (var item in pageData)
{
Console.WriteLine($"编号:{item.Id} 名称:{item.GoodsName}");
}
decimal totalPrice = goodsList.GetSum(g => g.Price);
Console.WriteLine($"商品总价:{totalPrice}");
var goodsDict = goodsList.ToMap(g => g.Id, g => g.GoodsName);
Console.WriteLine($"字典取值Id=2:{goodsDict[2]}");
Console.ReadLine();
}
}
}
扩展方法必须和调用代码同命名空间,或者手动using 命名空间名引入,统一包裹后即可正常识别扩展方法。

浙公网安备 33010602011771号