CSharp中的集合接口,类之间的关系

C#
本文总阅读量:

今天看到了一句话
the Where() LINQ extension method is used to filter for a particular set of URLs. Where(), like most LINQ methods, returns an IEnumerable value
让我好奇IEnumerable Icollection Ilist list之间到底是什么关系
顺带IEnumerable可以直接调用ToList变成list

首先我看看 IEnumerable:
1 // 摘要:
2 // 公开枚举器,该枚举器支持在指定类型的集合上进行简单迭代。
3 //
4 // 类型参数:
5 // T:
6 // 要枚举的对象的类型。
7 [TypeDependency(“System.SZArrayHelper”)]
8 public interface IEnumerable : IEnumerable
9 {
10 // 摘要:
11 // 返回一个循环访问集合的枚举器。
12 //
13 // 返回结果:
14 // 可用于循环访问集合的 System.Collections.Generic.IEnumerator
15 IEnumerator GetEnumerator();
16 }
IEnumerable 实现IEnumerable接口方法,那IEnumberable做什么的,其实就提高可以循环访问的集合。说白了就是一个迭代。

再来看看ICollection:
1 // 摘要:
2 // 定义操作泛型集合的方法。
3 //
4 // 类型参数:
5 // T:
6 // 集合中元素的类型。
7 [TypeDependency(“System.SZArrayHelper”)]
8 public interface ICollection : IEnumerable, IEnumerable
原来ICollection 同时继承IEnumerable和IEnumerable两个接口,按我的理解就是,ICollection继续它们2个接口而且扩展了方法,功能强多了。
由原来的步枪变成半自动步枪
我们继续看IList:

public interface IList : ICollection, IEnumerable, IEnumerable
靠 IList 继承它们三个接口,怪不得功能这么多啊,那应该属于全自动步枪了
最后来看看List:

public class List : IList, ICollection, IEnumerable, IList, ICollection, IEnumerable
这个时候大家仔细看看,它们都是接口,只有List 是类,不仅实现它们的接口,而且还扩展了太多的方法给我利用。哇靠,几乎所有功能都能实现了,简直是激光步枪

总结:IEnumerable接口就是规定了可以使用foreach遍历的集合,C#中几乎?所有集合都实现了该接口,linq查询出来的可以直接用IEnumerable引用

101个linq例子https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

关于linq to entity一个注意点

今天通过linq查询发现linq使用时

1
2
3
4
select new XXclass
{
XX = "1" + "2"
}

会报错,原因是linq to entity 转成tolist时并不支持C#里面string.format方法,所以查询的时候并不能使用字符串拼接