2年没弄C#,生疏了。。想弄个小程序,遇到这个问题。我有一个数组,里面可能有一些为空的元素,要把空元素除去。然后把数组的第一、第二个元素和 最后一个元素替换。大概意思是:
原数组:string[] list = {"a", "b", "", "d", "e", "f"};
新数组string[] newlist = {"f" , "d", "e", "f","a", "b" };

解决方案 »

  1.   

    List<string> listTemp = new List<string>();
    foreach(string s in list)
    {
        if(string.IsNullOrEmpty(s)) continue;
        listTemp.Add(s);
    }
    string[] newlist = listTemp.ToArray();
      

  2.   

    如果是vs2008,.net 3.0以上。或是vs2005+linq补丁。你可以用linq更简单。
    string[] list = { "a", "b", "", "d", "e", "f" };
    string[] newlist = list.Select(s=>s).Where(s => !string.IsNullOrEmpty(s)).ToArray();
      

  3.   

    或是换另一种linq的写法:
    string[] list = { "a", "b", "", "d", "e", "f" };
    string[] newlist = (from s in list where !string.IsNullOrEmpty(s) select s).ToArray();
      

  4.   

    var q=(from q in list 
    where q.Length>0 select q).ToArray();
    或List的LS方法
      

  5.   


      IList<string> result=new List<string>();
      for(int i=0;i<list.Count;i++)
      {
         string s=list[i];
         if(i==1)
           result.Add("要替代的值");
         else if (i==2)
           result.Add("要替代的值"); 
         else if (s.Trim()==string.Empty)
           continus;
         else if(i==list.count-1)
            result.Add("要替代的值"); 
         else
            result.Add(s);
      }
      return result.ToArray();
      

  6.   


    (from q in list
    where q.Length>0 
    select q).ToArrAy();
      

  7.   

    string[] list = { "a", "b", "", "d", "e", "f" };
    List<string> listTemp = new List<string>();
    foreach (string s in list)
    {
        if (string.IsNullOrEmpty(s)) continue;
        listTemp.Add(s);
    }
    listTemp.Insert(0, listTemp[listTemp.Count - 1]);
    listTemp.Add(listTemp[1]);
    listTemp.Add(listTemp[2]);
    listTemp.RemoveRange(1, 2);
    string[] newlist = listTemp.ToArray();