如何更改此代码以使其停止循环但显示相同的内容?

时间:2014-11-19 04:35:22

标签: c# arrays

我正在尝试对我的程序进行编码,以便在输入的阵列隔间被占用时,它会告诉用户哪些隔间是空的。但是,我不知道如何更改代码,以便它将停止循环但显示相同的东西。这是我的代码:

                for (int i = 0; i < compartmentno.Length; i++)
                {
                    if (compartmentno[i] == 0)
                    {
                        MessageBox.Show("Available compartments are" + (i + 1).ToString());
                    }
                }

如何制作它以便程序只显示包含所有可用分区的消息框而不是显示10个消息框?在此先感谢您的帮助!

6 个答案:

答案 0 :(得分:2)

您可以使用LINQ:

int availableCompartments = compartmentno.Count(x=> x == 0);

MessageBox.Show("Available compartments are:" + availableCompartments.ToString());

WORKING FIDDLE EXAMPLE

以下是公寓号码:

public static void Main()
{

  int [] compartmentNo = { 1,3,5,6,7,8,9,0,4,0};


  var availableCompartments = compartmentNo
                             .Select((value, index) => new {index, value})
                             .Where(x=> x.value == 0)
                             .Select(x=>x.index);

  int Count = availableCompartments.Count();

  string Values = String.Join(",",availableCompartments);

  Console.WriteLine(String.Format("No of Aparments : {0} and aprtments No : {1}",Count,Values));


}

UPDATED FIDDLE DEMO

答案 1 :(得分:1)

您可以在一个字符串中添加所有隔离专区,并在循环外部显示消息。

using System.Text;

StringBuilder compartments = new StringBuilder();
for (int i = 0; i < compartmentno.Length; )
                {
                    if (compartmentno[i] == 0)
                    {
                        compartments.Append(++i.ToString() + ", ");

                    }
                }

MessageBox.Show("Available compartments are" + compartments.ToString());

答案 2 :(得分:0)

试试这个:

int availableCompartments = 0;
for (int i = 0; i < compartmentno.Length; i++)
                {
                    if (compartmentno[i] == 0)
                    {
                        availableCompartments++;
                    }
                }
MessageBox.Show("Available compartments are " + availableCompartments.ToString());

请注意,这只会显示有多少个可用区域,而不是哪些区域。

答案 3 :(得分:0)

  

注意:您必须为此使用相同的循环,而不是每次在操作后显示一次都显示消息。

使用以下代码:

int avli = 0;
for (int i = 0; i < compartmentno.Length; i++)
{
    if (compartmentno[i] == 0)
    {
        avli++;
    }
}

MessageBox.Show("Available compartments are" + avli.ToString());

答案 4 :(得分:0)

你可以使用linq。

var avaiableItems= string.Join(",", compartmentno.Where(x => x == 0).Select((item, index) => index+1));
MessageBox.Show(string.Format("Available compartments are {0}",avaiableItems));

答案 5 :(得分:0)

用一行代码完成。 :)

它使用了不太知名的Linq Select语句的索引器

MessageBox.Show(String.Format("Available compartments are {0}", String.Join(", ", compartmentno.Select((s, i) => new {i, s}).Where(p=>p.s == 0).Select(p=>p.i +1))));