无法使用.Any()作为通用列表

时间:2014-09-10 22:49:12

标签: c# asp.net-mvc-3

我在控制器中有以下代码,我正在调用一个服务操作,它将返回List

我想使用response.Customers.Any(),因为我会寻找特定的客户。但有时候.Any()不存在。当我使用.Any()时会出现编译错误。

不确定它是否取决于我调用该操作的方式?因为我一直认为我们可以使用.Any()作为通用列表

控制器

public class Customer
{
    public Customer(ICustomerService customerService) 
    {
        this.CustomerService = customerService;
    }

     private ICustomerService CustomerService { get; set; }

    var response = this.ExecuteServiceCall(() => this.CustomerService.getCustomerResults());

    response.customers.Any(x => x.group == "A");

}

4 个答案:

答案 0 :(得分:1)

AnyIEnumerable<T>接口的扩展方法,但其实现位于Enumerable命名空间中的静态System.Linq类中。它看起来像这样:

using System;
namespace System.Linq
{
    public static class Enumerable
    {
        ...

        public static bool Any<TSource>(
            this IEnumerable<TSource> source,
            Func<TSource, bool> predicate)
        {
            foreach (var item in source)
            {
                if (predicate(item))
                {
                    return true;
                }
            }
            return false;
        }

        ...
    }
}

如果要将其用作扩展方法,则需要添加using System.Linq;语句。

或者,为了您的理解,您可以将其称为

bool b = System.Linq.Enumerable.Any(response.customers, x => x.group == "A");

答案 1 :(得分:0)

确保您已在类中包含System.Linq以便能够使用.Any()

using System.Linq;

答案 2 :(得分:0)

您必须先包含名称空间System.Linq

然后,如果您的response.customers

  • 实施IEnumerable<T>,你应该好好去。

  • 显然实施IEnumerable<T>,您需要将其投射到所需的界面:

    bool hit = ((IEnumerable<Customer>)(response.customers))
               .Any( x => x.group == "A" )
               ;
    
  • 没有实现IEnumerable<T>,但是实现了非通用IEnumerable,您需要以不同的方式进行投射:

    bool hit = response.customers
               .Cast<Customer>()
               .Any( x => x.group == "A" )
               ;
    

答案 3 :(得分:0)

客户列出了返回对象的属性,还是对象本身?这样的事情会起作用吗?

var customers = this.ExecuteServiceCall(() => this.CustomerService.getCustomerResults());

if (customers.Any(c => c.group == "A")
{
    . . .
}