IEnumerable相关使用
#region 初始化数据
public class Book
{
public int ID { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public int Price { get; set; }
}
private List<Book> getBook
{
get
{
List<Book> list = new List<Book>()
{
new Book() {Title = "Title1", Author = "Author1", Price = 10, ID = 1},
new Book() {Title = "Title2", Author = "Author2", Price = 20, ID = 4},
new Book() {Title = "Title3", Author = "Author3", Price = 10, ID = 1},
new Book() {Title = "TOMS", Author = "TOMS", Price = 12, ID = 3},
new Book() {Title = "vI", Author = "vI", Price = -1, ID = -7},
new Book() {Title = "EL", Author = "EL", Price = 100, ID = 9},
new Book() {Title = "WING", Author = "WING", Price = 120, ID = 10},
};
return list;
}
}
#endregion
扩展方法:
public static class ListExprition
{
/// <summary>
/// 在List集中,查找最大的值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="c"></param>
/// <returns></returns>
public static int? FindMax<T>(this IEnumerable<T> source, Func<T, int?> c)
{
int? temp = null;
foreach (var item in source)
{
if (temp ==null)
temp = c(item);
else if (temp < c(item))
temp = c(item);
}
return temp;
}
/// <summary>
/// 在List集中,查找最小的值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="c"></param>
/// <returns></returns>
public static int? FindMin<T>(this IEnumerable<T> source,Func<T,int?> c)
{
int? temp = null;
foreach (var item in source)
{
if (temp == null)
temp = c(item);
else if (temp > c(item))
temp = c(item);
}
return temp;
}
/// <summary>
/// 求和
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="c"></param>
/// <returns></returns>
public static int? MySum<T>(this IEnumerable<T> source, Func<T, int?> c)
{
int? temp = 0;
foreach (var item in source)
{
temp += c(item);
}
return temp = (temp == null) ? 0 : temp;
}
/// <summary>
/// 根据条件查询集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="c"></param>
/// <returns></returns>
public static IEnumerable<T> MyWhere<T>(this IEnumerable<T> source, Func<T, bool> c)
{
foreach (var item in source)
{
if (c(item))
{
yield return item;
}
}
}
public static IEnumerable<TResult> MySelect<T, TResult>(this IEnumerable<T> source, Func<T, TResult> c)
{
foreach (var item in source)
{
var v = c(item);
yield return v;
}
}
}
调用实例:
private void button1_Click(object sender, EventArgs e)
{
var list = getBook;
var expandBIG=list.FindMax(p=>p.ID); //查找最大的值
var expandMIN = list.FindMin(c => c.ID);//查找最小值
var expandSum = list.MySum(x => x.Price);//价格求和
var selectModel = list.MyWhere(x => x.ID == 1).ToList() ;//根据条件查询结果
var selectlist = list.MySelect(x => new { x.ID, x.Price }).ToList();
MessageBox.Show(expandSum.Value.ToString());
}

浙公网安备 33010602011771号