IEnumerable 和IEnumerable<T> 接口在 .NET 中是非常重要的接口,它允许开发人员定义foreach语句功能的实现并支持非泛型方法的简单的迭代,IEnumerable和IEnumerable<T>接口是 .NET Framework 中最基本的集合访问器。它定义了一组扩展方法,用来对数据集合中的元素进行遍历、过滤、排序、搜索等操作。
IEnumerable接口是非常的简单,只包含一个抽象的方法Get IEnumerator(T),它返回一个可用于循环访问集合的IEnumerator对象。
IEnumerable、IEnumerator、ICollection、IList、List
IEnumerator:提供在普通集合中遍历的接口,有Current,MoveNext(),Reset(),其中Current返回的是object类型。
IEnumerable: 暴露一个IEnumerator,支持在普通集合中的遍历。
IEnumerator<T>:继承自IEnumerator,有Current属性,返回的是T类型。
IEnumerable<T>:继承自IEnumerable,暴露一个IEnumerator<T>,支持在泛型集合中遍历。
扩展方法如下表所示:
下面列举几个扩展方法实现的示例:(VS 2014 环境)
示例1:
Sum扩展方法:
新建如下几个类:
Book.cs 如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IEnumerableSum
{
/// <summary>
/// 数据模型
/// </summary>
public class Book
{
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Shopping.cs 如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IEnumerableSum
{
/// <summary>
/// 表示 Book 对象集合
/// </summary>
public class Shopping
{
private ValueCalculator vc;
public Shopping(ValueCalculator vcParam)
{
vc = vcParam;
}
public IEnumerable<Book> Books { get; set; }
public decimal CalculateBookTotal()
{
return vc.ValueBooks(Books);
}
}
}
ValueCalculator.cs 如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IEnumerableSum
{
public class ValueCalculator
{
/// <summary>
/// 定义了一个单一的方法ValueBooks,使用了IEnumerable的Sum方法将传递给该方法的可枚举对象中每一个 Book 对象的Price 属性值在一起
/// </summary>
/// <param name="books">该方法的可枚举对象</param>
/// <returns></returns>
public decimal ValueBooks(IEnumerable<Book> books)
{
return books.Sum(b => b.Price);
}
}
}
PS: 如果不理解 books.Sum(b => b.Price) ,可以查看 C# lambda 表达式。也可以擦汗查看本人MVC中的 lambda 案例,参阅
ASP.NET + MVC5 入门完整教程四---MVC 中使用扩展方法Program.cs 如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IEnumerableSum
{
class Program
{
static void Main(string[] args)
{
decimal totalPrice;
Book[] books =
{
new Book { Name = "Coho Vineyard", Price = 25.2M },
new Book { Name = "Lucerne Publishing", Price = 18.7M },
new Book { Name = "Wingtip Toys", Price = 6.0M },
new Book { Name = "Adventure Works", Price = 33.8M }
};
ValueCalculator vc = new ValueCalculator();
Shopping sp = new Shopping(vc) { Books = books };
totalPrice = sp.CalculateBookTotal();
Console.WriteLine("The total weight of the packages is: {0}", totalPrice);
Console.ReadKey();
}
public decimal ValueBooks(IEnumerable<Book> books)
{
return books.Sum(b => b.Price);
}
}
}
运行结果如下图所示:
其他扩展方法具体实现可参见官方示例 点击打开链接