[英]How can I iterate through an array and skip any empty items?
我已經從Excel文件中提取了一個csv,並將其放入數據表中。 excel csv文件中的某些單元為空,當我對其進行迭代時,也會對其進行迭代。 我希望不要迭代它們。
foreach (DataRow datarow in sorted.Rows)
{
Boolean first = true;
Console.Write(Environment.NewLine);
foreach (var item in datarow.ItemArray)
{
if (item != null)
{
int i = 0;
if (first)
first = false;
else
Console.Write(",");
Console.Write(item);
}
else
break;
}
}
我已經嘗試了上面的方法,它仍然會遍歷空單元格。
擴展JohnD答案,您可以嘗試一下,假設您只想將字段輸出到控制台 :
var text = string.Empty;
foreach (DataRow datarow in sorted.Rows)
{
var items = datarow.ItemArray
.Where(x => ((x != null) && !string.IsNullOrEmpty(x.ToString())));
var textJoined = string.Join(",", items);
text += textJoined + Environment.NewLine;
}
Console.WriteLine(text);
您可能不熟悉LINQ,因此您將需要以下using語句:
using System.Linq;
同樣,此解決方案假定您只想將值輸出到控制台窗口,而不假定您要遍歷給定行的所有列。 如果您要這樣做,請告訴我,我可以進行適當的修改
[edit]哎呀,只是重新閱讀了您的問題,看來您確實想遍歷每列,因此下面是一個解決方案:
var text = string.Empty;
foreach (DataRow datarow in sorted.Rows)
{
var items = datarow.ItemArray
.Where(x => ((x != null) && !string.IsNullOrEmpty(x.ToString())));
var currentLine = string.Empty;
foreach(var item in items)
{
// do something with item
// in this case append to currentLine
currentLine += item + ",";
}
text += currentLine.Substring(0, currentLine.Length - 2) + Environment.NewLine;
}
Console.WriteLine(text);
您得到相同的結果,現在您可以做每個項目所需的事情
假設該項目確實是一個字符串,請檢查item
為空或空使用String.IsNullOrEmpty()
if (item != null && !String.IsNullOrEmpty(item.ToString()))
foreach (DataRow datarow in sorted.Rows)
{
Boolean first = true;
Console.Write(Environment.NewLine);
foreach (var item in datarow.ItemArray)
{
if (!string.IsNullOrEmpty((item ?? "").ToString()))
{
int i = 0;
if (first)
first = false;
else
Console.Write(",");
Console.Write(item);
}
else
continue;
}
}
為什么不這樣呢?
// ItemArray is object[]
foreach (var item in datarow.ItemArray)
{
if (first)
{
first = false;
}
else
{
// I think you are expecting to see the comma here even the previous element is empty e.g. A,B,,D (that missing C)
Console.Write(",");
}
// so here we cannot guarantee "if (item is string)"
if (item != null)
{
Console.Write(item.ToString());
}
}
(我的習慣是將所有代碼包裝在{}中)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.