2017-10-25 2 views
0

私はこのコードを持っています。私は0より大きい配列の部分だけを表示したいと考えています。 たとえば...数字の束が入力され、変数として格納されます。しかし、配列内のすべての変数が使用されるわけではありません。配列を表示すると、数字は "140、180、298、130、0、0、0、 0、0、0 "など。 ゼロを表示したくありません。どのようにゼロを出力から除外するのですか?

int[] scores = {score1, score2, score3, score4, score5, score6, score7, score8, score9, score10, score11, score12, score13, score14, score15}; 

Console.WriteLine("Your scores as you entered them: " + (string.Join(", ", scores))); 
Console.ReadKey(); 
+0

私は疑いますループをどこかで使用して、別の変数ではなく最初のリストに配置することができます –

+1

'List 'の使用を検討してください。サイズが固定されているため、ゼロが含まれている配列ではなく、その配列に追加します。 –

+1

答えとして1つの回答を受け入れてください。これは、このスレッドを読む他のコミュニティーのメンバーにとって有益です。 – Oswald

答えて

8

使用LINQのWhere:あなた以上の説明では

string.Join(", ", scores.Where(x => x != 0)) 

も0より大きい配列の部分は語りました。だから、あなたがそれを変更できる場合であれば:取得するには

List<int> result = new List<int>(); 
foreach(int item in scores) 
{ 
    if(item != 0) 
     result.Add(item); 
} 
+0

LinQ以外のソリューションを削除してください。答はクリスタルクリアなので。 –

+1

@NuriYILMAZ - linqを削除する必要はありませんが、linqが行く方法だと思っています。これがOPのために進んでいれば、よりシンプルなバージョンです。 –

+0

@Michael M - 喜んで –

0

List<int>と、単純なforeachの(またはのために)ループを使用する非LINQソリューションについて

string.Join(", ", scores.Where(x => x > 0)) 

あなたの質問の答えはGilad Greenの答えを見ています。

私が見ているコードについてちょっとフィードバックをいただきました。

私はあなたのコードをすべて見ていないので、ここではたくさんの仮定をしています。私が間違っているとすみませます。

15個の値で配列を塗り潰す場合は、コードをリファクタリングしてループを使用することを検討する必要があります。

次の例では、forループを使用しますが、異なるループで解決できます。

int[] scores = new int[15]; //initialize an array of ints with a length of 15 
for (int i = 0; i < scores.Length; i++) //loop from 0 till smaller than the length of the array (0-14 = 15 iterations) 
    scores[i] = int.Parse(Console.ReadLine()); //fill the scores array with the index of i with the console input 
1

あなたはまだLINQを理解していない場合は、コードのこの作品に見ることができます。

int[] scores = { 1, 2, 3, 0, 0, 4, 5, 0, 0, 6}; 

int[] withoutZeros = WithoutZeros (scores); 

とコア方法:このような15変数を持つ

public static int[] WithoutZeros (int[] input) 
{ 
    int zerosCount = 0; // we need to count how many zeros are in the input array 

    for (int i = 0; i < input.Length; i++) 
    { 
     if (input[i] == 0) zerosCount = zerosCount + 1; 
    } 

    // now we know number of zeros, so we can create output array 
    // which will be smaller than then input array (or not, if we don't have any zeros in the input array) 

    int[] output = new int[input.Length - zerosCount]; // can be smaller, equal, or even empty 

    // no we need to populate non-zero values from the input array to the output array 

    int indexInOutputArray = 0; 

    for (int i = 0; i < input.Length; i++) 
    { 
     if (input[i] != 0) 
     { 
      output[indexInOutputArray] = input[i]; 

      indexInOutputArray = indexInOutputArray + 1; 
     } 
    } 

    return output; 
} 
+2

非linqソリューションのためのより簡単な方法があります..また、 'x = x + 1'の代わりに' ++ '演算子を使用することを検討してください。 –

+0

はい、また多くのバグは" LinQ以外の解決策 "です。私はそれらを数えることを好むべきではありません。 –

関連する問題