2011-12-08 7 views
0

私は現在、2つのアレイ1店舗のファイルサイズを格納するファイル名と別のものを持っています。私は、最大ファイルサイズとその名前の両方を表示する必要があります。このコードを使って最大のファイルを表示することができます。C#の取得配列の要素数

 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); 

私はgoogleを使用しようとしましたが、最大値または最小値の仕組みを教えています。

+0

は、アレイを使用する必要があります要件はありますか? – user1231231412

+0

アレイを使用する必要がありますか?あなたが使用できる名前と値のペアを格納するネイティブの.NETコレクションオブジェクトがたくさんあります。また、柔軟性を最大限に高めるために、常にSystem.Data.Datatableオブジェクトがあります。ファイルの名前とサイズ、および他の属性を同じ行に保持し、この不要な複雑さを排除することができます。 – David

+0

私が使用しなければならない要件はありません。最大のファイルのサイズと名前を表示するだけです。 – bobthemac

答えて

4

を管理し、現在の最大ファイルサイズを追跡するのは難しいですし、それはで名前です別々の変数。このような何か:

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. 
4

辞書代わりのアレイを使用することを検討してください。配列が同期して得るかもしれないし、それはあなたのfiles配列の上に名前とサイズ、ちょうどループのための別々の配列の必要はありません

 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); 
0

Maxは、あなたのインデックス検索が動作しない理由です、最大を返し、ない最大値のインデックス

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>を使用するか、またはあなたが前に持っていたとしても、ファイルの種類:あなたはこれを試してください。

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); 
     } 
関連する問題