2年没弄C#,生疏了。。想弄个小程序,遇到这个问题。我有一个数组,里面可能有一些为空的元素,要把空元素除去。然后把数组的第一、第二个元素和 最后一个元素替换。大概意思是:
原数组:string[] list = {"a", "b", "", "d", "e", "f"};
新数组string[] newlist = {"f" , "d", "e", "f","a", "b" };
原数组:string[] list = {"a", "b", "", "d", "e", "f"};
新数组string[] newlist = {"f" , "d", "e", "f","a", "b" };
foreach(string s in list)
{
if(string.IsNullOrEmpty(s)) continue;
listTemp.Add(s);
}
string[] newlist = listTemp.ToArray();
string[] list = { "a", "b", "", "d", "e", "f" };
string[] newlist = list.Select(s=>s).Where(s => !string.IsNullOrEmpty(s)).ToArray();
string[] list = { "a", "b", "", "d", "e", "f" };
string[] newlist = (from s in list where !string.IsNullOrEmpty(s) select s).ToArray();
where q.Length>0 select q).ToArray();
或List的LS方法
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();
(from q in list
where q.Length>0
select q).ToArrAy();
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();