使用的string.join時刪除空空我知道我們可以用下面使用的string.join時取出空或空數組:C#.NET 2.0中
var res = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s)));
我已經嘗試過這一點。網絡2.0,但不能。很抱歉聲明,但我必須爲我的應用程序使用.net 2.0。 .net 2.0有什麼辦法嗎?
使用的string.join時刪除空空我知道我們可以用下面使用的string.join時取出空或空數組:C#.NET 2.0中
var res = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s)));
我已經嘗試過這一點。網絡2.0,但不能。很抱歉聲明,但我必須爲我的應用程序使用.net 2.0。 .net 2.0有什麼辦法嗎?
你可以使用一個醜陋的黑客喜歡加入/分割/結合:
string res = string.Join(",",
(string.Join(",", array).split(",",
StringSplitOptions.RemoveEmptyEntries));
'var'關鍵字是一個編譯器功能,而不是.NET功能。只要您使用足夠現代的編譯器/ Visual Studio,它就可以與您使用的任何框架版本一起工作。 – Konamiman
@Konamiman謝謝,我不知道。編輯我的答案,刪除該筆記。 –
遍歷您的數組:
var tmp = new List<string>();
foreach(var s in array)
{
if (!string.IsNullNorEmpty(s)) tmp.Add(s);
}
var res = string.Join(",", tmp.ToArray());
如果您想要(有點)推出你自己的,並且需要你的項目在多個地方,你可以推出你自己的「LINQ擴展」(顯然是n OT擴展方法,因爲你的目標.NET 2.0),但...
的重要說明:
Where()
,這個貪婪地評估給定集合,因此,如果它給了一個IEnumerable
那不會結束,這會導致無限循環。的靜態方法:
public static class EnumerableExtensions {
public delegate TResult Func<T, TResult>(T t);
public static T[] Where<T>(IEnumerable<T> e, Func<T, bool> func) {
IList<T> result = new List<T>();
foreach (T each in e) {
if (func(each)) {
result.Add(each);
}
}
T[] returnValue = new T[result.Count];
result.CopyTo(returnValue, 0);
return returnValue;
}
}
及用途:
string[] array = {"a", "b"};
string res = string.Join(
",",
EnumerableExtensions.Where(array, delegate(string s) { return !string.IsNullOrEmpty(s); })
);
就我所知,在.NET 2.0中不可能使用類型(方差和協方差),也不能啓用LAMBDA語法。 – HimBromBeere
@HimBromBeere我寫這個時候的目標是2.0。 – jdphenix
事實上,它對C#3.0向上工作,然而它不一定適用於.NET 2.0 – HimBromBeere
這工作,但我不知道的性能。
string res = string.Join(",", Array.FindAll(array, delegate(string s)
{
return !string.IsNullOrEmpty(s);
}));
你可以輕鬆地重新編寫代碼來做你想做的事。 .NET 2.0不支持LINQ表達式。該代碼基本上在數組中找到當前項不爲空或空的項目,然後最終將數組連接在一起。 –
爲什麼不只是刪除數組中的空對象並將它們連在一起後綴? – ckruczek