C# System.Array' 不包含 'Count' 的定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19776715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:51:41  来源:igfitidea点击:

System.Array' does not contain a definition for 'Count'

c#asp.net

提问by Siddiq Baig

In my C# Project, I am getting this error that the definition for count does not contain System.Array

在我的 C# 项目中,我收到此错误,即计数的定义不包含 System.Array

protected void Page_Prerender(object sender, EventArgs e)
{
    FileInfo[] fileInfo;
    string UpFolder = Server.MapPath("~/data/images/");
    DirectoryInfo dir = new DirectoryInfo(UpFolder);
    fileInfo = dir.GetFiles();
    // here i am getting error
    int TotalImages = fileInfo.Count();
    for (int count = 0; count < TotalImages; count++)
    {
        Image image = new Image();
        image.ImageUrl = "~/data/images/" + fileInfo[count].ToString();
        image.ID = count.ToString();
        DataListImage.Controls.Add(image);
    }
    DataListImage.DataSource = dir.GetFiles();
    DataListImage.DataBind();

    string UpFolder1 = Server.MapPath("~/data/thumbnails/");
    DirectoryInfo dir1 = new DirectoryInfo(UpFolder1);
    DataListthumbnails.DataSource = dir1.GetFiles();
    DataListthumbnails.DataBind();
}

采纳答案by Habib

You don't need Count, instead you can use Lengthwith arrays to get the count.

您不需要Count,而是可以使用Length数组来获取计数。

You are getting the error since you are missing using System.Linq;

由于您丢失,您收到错误 using System.Linq;

To get TotalImagesyou can use

为了让TotalImages你可以使用

int TotalImages = fileInfo.Length;

回答by user2864740

While Count()isn't "needed"since the type is an Array, the error is a result of not "using" the correct namespaces.

虽然Count()不是“需要”,因为类型是一个数组,但错误是没有“使用”正确的命名空间的结果。

Enumerable.Count()is a LINQ extensionmethod in the System.Linqnamespace. As such, it can be made available with the following:

Enumerable.Count()是命名空间中的 LINQ扩展方法System.Linq。因此,它可以通过以下方式提供:

using System.Linq;

Since arrays implement IEnumerable<T>, then they can utilize any such methods when they are made available.

由于数组实现了IEnumerable<T>,因此它们可以在可用时使用任何此类方法。