如何为C#泛型集合获取一致的.Count/.Length属性?

mik*_*kel 4 c# generics collections

List<T>.Count属性,而不是T<>数组.Length.我认为这是因为数组是固定长度而其他数组不是,但语法上的差异仍然令人沮丧.

如果你从一个数组重构列出,因此它提供了"不包含定义.长度"的错误,似乎具有浪费时间去改变它时.Count,并.Length在本质上是相同的.

有没有一个好方法来处理这个?是否可以扩展List<T>以添加例如.Length别名的属性,.Count反之亦然?无论出于何种原因,这都是一个坏主意吗?

Luk*_*keH 6

您可以使用CountLINQ提供的方法.

这被优化为尽可能使用接口Count提供的属性ICollection<T>(或ICollection.NET 4中的非泛型接口).所以阵列List<T>等都将被优化.

var yourList = new List<string> { "the", "quick", "brown", "fox" };
int count1 = yourList.Count();  // uses the ICollection<T>.Count property

var yourArray = new[] { 1, 2, 4, 8, 16, 32, 64, 128 };
int count2 = yourArray.Count();  // uses the ICollection<T>.Count property

var yourEnumerable = yourArray.Where(x => x > 42);
int count3 = yourEnumerable.Count();  // no optimisation, iterates the sequence
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要某种类型的一致计数属性而不存在在非优化情况下迭代整个序列的风险,那么您可以创建自己的扩展方法.(我个人不会走这条路.)

int count4 = yourList.GetCount();  // uses the ICollection<T>.Count property
int count5 = yourArray.GetCount();  // uses the ICollection<T>.Count property
int count6 = yourEnumerable.GetCount();  // compile-time error

// ...

public static class CollectionExtensions
{
    public static int GetCount<T>(this ICollection<T> source)
    {
        if (source == null) throw new ArgumentNullException("source");
        return source.Count;
    }

    public static int GetCount(this ICollection source)
    {
        if (source == null) throw new ArgumentNullException("source");
        return source.Count;
    }
}
Run Code Online (Sandbox Code Playgroud)