在 .Count() 之后创建 ICollection<T> 的扩展方法

Create Extension Method of ICollection<T> after .Count()

我正在尝试创建一个非常简单的扩展方法,如果任何 Collection 的计数等于一,则 returns 为真或假。我有相应的方法。但是那个方法运行是里面的.Count()。思路是运行只校验后的计数,例如:myList.Count().EqualsToOne();

我不知道它是否与接收函数和调用它有关(我认为它是一样的)。

这是实现:

public static class ExtensionMethods
{
    public static bool EqualsToOne<T>(this ICollection<T> sequence)
    {
        int count = sequence.Count();

        if(count == 1)
        {
            return true;
        }

        return false;
    }
}


static void Main(string[] args)
{
    Employee emp = new Employee() { Id = 1 };

    List<Employee> lstEmployee = new List<Employee>()
    {
        emp,
    };

    //The idea should be lstEmployee.Count().EqualsToOne()
    bool result = lstEmployee.EqualsToOne(); 

    Console.WriteLine(result.ToString());
    Console.ReadLine();

    lstEmployee.Add(emp);

    result = lstEmployee.EqualsToOne();

    Console.WriteLine(result.ToString());
    Console.ReadLine();

}

我不知道你为什么想要这个。但这里是:Count() returns 一个 intint 是你想要扩展的:

public static bool EqualsToOne(this int i) => i == 1;

但实际上,如果这只是关于ICollection<T>的实例,这个接口已经提供了属性Count。不需要使用 linq 的 Count() 扩展。只需 collection.Count == 1 即可。

如果您想将其扩展到其他 IEnumerable<T> 个实例,如果您只想知道它只是一个元素,我会避免 Count() 整个序列。

所以我会将您的第一个实现更改为:

public static bool SequenceHasExactlyOneElement<T>(this IEnumerable<T> source)
{
    if (source == null) throw new ArgumentNullException(nameof(source));

    using(var enumerator = source.GetEnumerator())
        return enumerator.MoveNext() && !enumerator.MoveNext();
}