c#获取数组元素号

时间:2011-12-08 15:00:49

标签: c# arrays numbers max

我目前有两个数组,一个存储文件名,另一个存储文件大小。我需要显示最大文件大小及其名称。我可以通过使用此代码来显示最大的文件。

        long[] fileSize;
        string[] fileName;
        fileSize = new long[fileCount];
        fileName = new string[fileCount];
        for (int index = 0; index < files.Length; index++)
        {
            fileSize[index] = files[index].Length;
            fileName[index] = files[index].Name;
        }
        long largestFile = fileSize.Max();
        string latestFileName = fileName[fileSize.Max()];
        Console.WriteLine("Total size of all files: {0}", totalSize);
        Console.WriteLine("Largest file: {1}, {0}", largestFile, latestFileName );

我尝试使用谷歌,但它只是告诉我如何计算最大值或最小值。

4 个答案:

答案 0 :(得分:4)

考虑使用Dictionary而不是数组。数组可能会失去同步,而且管理难度很大

        var info = new Dictionary<string, long>();
        info.Add("test.cs", 24);
        var maxSize = info.Values.Max();
        Console.WriteLine(info.Single(p => p.Value == maxSize).Key);

答案 1 :(得分:4)

不需要为名称和大小设置单独的数组,只需循环遍历files数组,并在单独的变量中跟踪当前的最大文件大小及其名称。像这样:

int max = 0;
string name = string.Empty;

for (int index = 0; index < files.Length; index++)
{
    int size = files[index].Length;
    //check if this file is the biggest we've seen so far
    if (size > max)
    {
        max = size; //store the size
        name = files[index].Name; //store the name
    }
}

//here, "name" will be the largest file name, and "max" will be the largest file size.

答案 2 :(得分:1)

        var largestFiles = files.Where((f1) => f1.Length == files.Max((f2) => f2.Length));

        // it's possible that there are multiple files that are the same size and are also the largest files.
        foreach (var file in largestFiles)
        {
            Console.WriteLine("{0}: {1}", file.Name, file.Length);
        }

答案 3 :(得分:0)

Max返回最大,而不是最大值 index ,这就是您的索引查找不起作用的原因。你可以试试这个:

long largestSize = -1;
int largest = -1;
for (int index = 0; index < files.Length; index++)
{
    fileSize[index] = files[index].Length;
    fileName[index] = files[index].Name;

    if(fileSize[index] > largestSize)
    {
        largestSize = fileSize[index];
        largest = index;
    }
}

或者,正如其他人指出的那样,使用Tuple<string, long>Dictionary<string, int>数组(如果文件名是唯一的),甚至是之前的文件类型。