日期:2014-05-18  浏览次数:21294 次

c#如何为foreach语句中的空值赋值?
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
  class Program
  {
  static void Main(string[] args)
  {
  //Program mytest = new Program();
  //Console.WriteLine(testing());

  testing();
  }

  private static string testing()
  {
  //string sum = "";
  string[] arr = new string[5];
  arr[1] = "5";
  arr[3] = "51";
  arr[4] = "52";
  foreach (string i in arr)
  {
  if (i=="")
  {
  i="空";
  }
   
  Console.WriteLine(i);

  }
  //return sum;
  return arr.ToString();
  }
  }
}

调试的结果出错
提示为:“i是一个foreach变量,无法为它赋值”

------解决方案--------------------
for (int i =0;i<arr.lenght,i++)
{
if (arr[i]=="")
{
arr[i]="空";
}

Console.WriteLine(i);

}

------解决方案--------------------
string[] arr = new string[5];
arr[1] = "5";
arr[3] = "51";
arr[4] = "52";
int ii = 0;
foreach (string i in arr)
{
if (i == "")
{
arr[ii] = "空";
}
ii++;
}
------解决方案--------------------
string[] arr = new string[5];
arr[1] = "5";
arr[3] = "51";
arr[4] = "52"; 
arr = (from string _string in arr select (_string ==null?"空":_string)).ToArray();