Reputation: 1172
I currently have two arrays one the stores a file name and another that stores the file size. I need to show both the maximum file size and its name. I can get it to show the largest file by using this code.
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 );
I have tried using google but it just tells me how to work out the maximum or minimum.
Upvotes: 0
Views: 3346
Reputation: 13483
Consider using Dictionary instead of arrays. Arrays might get out of sync and it's harder to manage
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);
Upvotes: 4
Reputation: 10280
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);
}
Upvotes: 1
Reputation: 12513
Max
returns the maximum value, not the maximum value's index, that's why your index lookup does not work. You may try this:
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;
}
}
Or, as others pointed out, use an array of Tuple<string, long>
, a Dictionary<string, int>
(if file names are unique), or even the file types you had before.
Upvotes: 0
Reputation: 37516
There's no need for separate arrays for the name and size, just loop over your files
array, and keep track of the current max file size and it's name in separate variables. Something like this:
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.
Upvotes: 4