IEnumerable、ICollection、IList、List之间的区别与方法介绍

时间:2023-03-09 04:54:16
IEnumerable、ICollection、IList、List之间的区别与方法介绍

区别

以下列出IEnumerable、ICollection、IList、List继承关系。(这里带有泛型,非泛型也是一样的关系)

IEnumerable<T>:

public interface IEnumerable<out T> : IEnumerable

ICollection<T>:

public interface ICollection<T> : IEnumerable<T>, IEnumerable

IList<T>:

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable

List<T>:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>,
IEnumerable, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>

功能多少排序:List > IList > ICollection > IEnumerable。

方法介绍

由于上面的枚举类和接口都有好多方法,所以只介绍下我最近常用的。

IEnumerable:

1、All<TSource>(Func<TSource, Boolean>) :判斷序列中的所有項目是否全都符合條件。

class Pet
{
public string Name { get; set; }
public int Age { get; set; }
} public static void AllEx()
{
// Create an array of Pets.
Pet[] pets = { new Pet { Name="Barley", Age= },
new Pet { Name="Boots", Age= },
new Pet { Name="Whiskers", Age= } }; // Determine whether all pet names
// in the array start with 'B'.
bool allStartWithB = pets.All(pet =>
pet.Name.StartsWith("B")); Console.WriteLine(
"{0} pet names start with 'B'.",
allStartWithB ? "All" : "Not all");
}

2、 GetEnumerator:获取序列,以遍历。

今天先写到这。