关于C#中的数组的问题 [英] Question about arrays in C#

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

问题描述

我有

I have

string[] filenames = Directory.GetFiles(@"C:\temp\test", "*.png", SearchOption.AllDirectories);

string[] myArr = new string[10];





private void btnLoadTrainingData_Click(object sender, EventArgs e)
{
            foreach (string f in filenames)
            {                
                img = (Bitmap)Bitmap.FromFile(f);
                Console.WriteLine(convertToBinary(img));            
            }
}


方法"convertToBinary"返回转换后的图像的字符串值"1"和"0".

我需要的是如何将每个返回值的字符串存储在数组+文件名中.

我想要这样的东西:
A_001.png 100100011
A_002.png 100110011
B_001.png 001110111




我已经尝试实现一个数组(请参见下文),但是我总是在获取最后一个打开的文件.


The method ''convertToBinary'' returns a string value of 1''s and 0''s of the converted image.

What I need is how to store the string of each returned value in an array + the filename.

I want something like this:
A_001.png 100100011
A_002.png 100110011
B_001.png 001110111
etc



I have tried to implement an array (see below) but I am always getting the last file that was opened.

private void populateArray(string binVal)
    {
        for (int j = 0; j < myArr.Length; j++)
        {
            //for (int j = 0; j < 2; j++)
            myArr[j] = (binVal);
        }

推荐答案

您可以修改现有的foreach循环:
You could just modify your existing foreach loop:
int i = 0;
foreach (string f in filenames){                
   img = (Bitmap)Bitmap.FromFile(f);
   myArr[i++] = f + " " + convertToBinary(img);            
   if (i >= myArr.Length) {
      break;
      }
   }

但是,我承认我对为什么要一开始这样做感到茫然! :laugh:

But I will admit I am at a loss as to why you would want to do this in the first place! :laugh:


虽然我相信OriginalGriff已经正确回答了这个问题,但我会把它扔进锅里只是为了增加一点不同的味道.

@ bmw318mt:

1.您的当前代码为何在每个数组元素中都使用相同的二进制字符串值,这没有什么神秘之处:您只需向其传递一个值!

2.您是否为"myArr"分配了固定大小的十个元素,因为这就是您想要的全部;并且,您确定目录搜索的结果将始终返回至少十个元素吗?

3.注意:此示例仅使用一个字符串数组,但没有理由不使用它们中的两个,这可能会使使用两个中的代码更加清晰.

考虑:
While I believe OriginalGriff has answered this question correctly, I''ll throw this in the pot just to add a slightly different flavor.

@bmw318mt:

1. There''s no mystery why your current code sticks the same binary-string value in each array element: you are only passing it one value !

2. Do you assign ''myArr a fixed size of ten elements because that''s all you want; and, are you sure the result of the Directory Search will always return at least ten elements ?

3. Note: this example uses only one string array, but there''s no reason not to use two of them, and it might make the code clearer to use two of them.

Consider:
// other required 'using statements
using System.IO;
//
// Class scoped variables
private string[] fileNames;
private string testFilePath = @"C:\temp\test";
private string testFileType = @"*.png";

private void populateArray(string filePath, string fileType)
{
    try
    {
        fileNames = Directory.GetFiles(filePath, fileType, SearchOption.AllDirectories);
    }
    catch (DirectoryNotFoundException ex)
    {
        MessageBox.Show("Error: " + ex.Message);
        // we're dead: give up the ghost !
        return;

    }

    // method scoped variable
    Bitmap img;

    for (int j = 0; j < fileNames.Length; j++)
    {
        img = (Bitmap)Bitmap.FromFile(fileNames[j]);
        // here we use your convertToBinary method
        // which you do not show us the code for
        fileNames[j]+= " " + convertToBinary(img);
    }
}
//
// so, you'd call the code like this:
// populateArray(testFilePath, testFileType);

现在,让我们迈出第一步返回,并考虑使用Directory.GetFiles时发生错误的可能性...我们已经证明了捕获上述一种错误:您可能要考虑是否处理此File.IO的几种特定可能错误中的一种或多种.方法...请参阅:[ ^ ] ...或使用相同的错误处理程序处理所有可能的错误消息...但是,恕我直言,您应该使用GetFiles之类的方法来考虑错误的可能性!我曾经使用'AllDirectories选项遇到一个错误,是由于一个子文件夹没有访问权限引起的.

如果在指定目录中找到大量匹​​配的文件怎么办?那是问题吗 ?使用此处的技术,您不能只是吃到饱",然后停止:

因此,如果您真正想要的只是十个文件路径或其他任意数量的文件路径...?

进一步向前看:字符串数组,其中文件的文件名与文件内容的二进制表示形式(逐字节)串联在一起……假设您想使用现在合并为一个数组的两条信息element ...意味着要访问给定文件的二进制数据,您将需要使用一个数组元素并以某种方式拆分"它:这是非常低效且不必要的.

因此,您还可以如何设计数据结构以保留文件名和二进制表示形式之间的链接:Dictionary< string,string>是可以在这里使用的一种选择,因为我们可以假定任何一个文件的完整文件路径都是唯一的,并且可以用作每个Dictionary项的Key;自然,二进制表示形式将成为给定词典项的键的值.

Now, let''s take one step back, and consider the possibilities of errors in your using Directory.GetFiles ... we''ve demonstrated catching one kind of error above: you may want to consider whether to handle one or more of several specific possible errors of this File.IO method ... see: [^] ... or handle all possible error messages with the same error handler ... but, imho, you should think about the possibilities of errors using a method like GetFiles ! An error I once encountered using the ''AllDirectories option was caused by one sub-folder not having access permission.

What if you find some enormously large number of files that match in a specified directory ? Is that a problem ? Using the techniques here, you cannot just "eat until full," then stop:

So, if all you really want is ten filepaths, or some other arbitrary number ... ?

Looking one step further: your array of strings where the file name of the file is concatenated with a binary representation of file contents (byte-by-byte) essentially ... assuming you want to use both pieces of information now merged into one array element ... means that to access a given file''s binary data, you are going to have take an array element and "split it" in some way: that''s very inefficient, and unnecessary.

So, how else might you design your data structure to preserve the linkage between file name and binary representation: a Dictionary<string,string> is one choice that can be used here, since we can assume the complete filepath of any one file is unique, and can be used as the Key for each Dictionary item; naturally, the binary representation would become the Value of the Key for the given Dictionary item.


这篇关于关于C#中的数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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