我有一個可怕的方法,從DataTable中提取數據並將其轉換爲所需格式的DataTable。我相信在LinQ中有更好的方法來做到這一點,但我並沒有真正體驗過它。如果有人能給我一個更好的解決方案,我將不勝感激。如何將嵌套for循環與if條件轉換爲LINQ
赫雷什代碼
private static void ExtractImportLayoutFromExcelDt(DataTable importDt, DataTable dtExtracted, int languages)
{
// The number of Locale colums included in the excel file.
for (int x = 0; x < languages; x++)
{
// The total number of friendlynames-keys/language included in the excel.
for (int j = 0; j < dtExtracted.Rows.Count; j++)
{
var row = dtExtracted.Rows[j];
DataRow tempRow = importDt.NewRow();
// Filling in the 3 columns. (FriendlyName - LocaleID - Text)
for (int i = 0; i <= 2; i++)
{
if (i == 0)
{
tempRow[i] = row[i]; // Friendly names: This is always going to be column 1 [0].
}
else if (i == 1)
{
tempRow[i] = Regex.Match(dtExtracted.Columns[x + 1].ToString(), @"\d+").Value; // LocaleIDs: Getting rid of non numeric characters from this column.
}
else
{
tempRow[i] = row[x + 1];
}
}
importDt.Rows.Add(tempRow);
}
}
}
對於初學者來說,使用所有這些不正確的命名變量(如果需要註釋,重寫)很難閱讀。到目前爲止,你自己上來了什麼? –
老實說Linq更適合將'foreach'轉換爲'for'。 – juharr
你完全確定你需要最裏面的'for'循環嗎? – bashis