IEnumerable的不具有计数方法 [英] IEnumerable doesn't have a Count method

查看:200
本文介绍了IEnumerable的不具有计数方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方式:

 公共BOOL的IsValid
{
  {返回(GetRuleViolations()计数()== 0); }
}公共IEnumerable的< RuleViolation> GetRuleViolations(){
  // code在这里
}

为什么,当我这样做 .Count之间的()上面是红色下划线?

我得到了以下错误:


  

错误1'System.Collections.Generic.IEnumerable
  不包含一个定义
  计数,并没有扩展方法
  计数接受的第一个参数
  类型
  System.Collections.Generic.IEnumerable
  可以找到(是否缺少
  使用指令或程序集
  参考)C:\\用户\\ A \\文档\\ Visual
  工作室
  2010 \\项目\\的NerdDinner \\的NerdDinner \\ \\型号15 Dinner.cs 47的NerdDinner



解决方案

您添加:

 使用System.Linq的;

在源代码的顶部,并确保你已经到了System.Core程序集的引用。

计数() 是由<提供的扩展方法href=\"http://msdn.microsoft.com/en-us/library/bb345746%28v=VS.100%29.aspx\"><$c$c>System.Linq.Enumerable静态类的LINQ to对象,<一个href=\"http://msdn.microsoft.com/en-us/library/system.linq.queryable%28v=VS.100%29.aspx\"><$c$c>System.Linq.Queryable对LINQ to SQL和其他外的过程提供商。

编辑:事实上,使用计数()这里是效率相对较低(至少在LINQ到对象)。所有你想知道的是是否存在的任何的元素或没有,对不对?在这种情况下,任何()是一个更适合:

 公共BOOL的IsValid
{
  {返回GetRuleViolations()任何()!。 }
}

I have the following method:

public bool IsValid
{
  get { return (GetRuleViolations().Count() == 0); }
}

public IEnumerable<RuleViolation> GetRuleViolations(){
  //code here
}

Why is it that when I do .Count() above it is underlined in red?

I got the following error:

Error 1 'System.Collections.Generic.IEnumerable' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?) c:\users\a\documents\visual studio 2010\Projects\NerdDinner\NerdDinner\Models\Dinner.cs 15 47 NerdDinner

解决方案

You add:

using System.Linq;

at the top of your source and make sure you've got a reference to the System.Core assembly.

Count() is an extension method provided by the System.Linq.Enumerable static class for LINQ to Objects, and System.Linq.Queryable for LINQ to SQL and other out-of-process providers.

EDIT: In fact, using Count() here is relatively inefficient (at least in LINQ to Objects). All you want to know is whether there are any elements or not, right? In that case, Any() is a better fit:

public bool IsValid
{
  get { return !GetRuleViolations().Any(); }
}

这篇关于IEnumerable的不具有计数方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆