我有一个包含两列的 DataTable:JobDetailID 和 CalculatedID。JobDetailID 并不总是唯一的。我希望给定 JobDetailID 的一个/第一个 CalculatedID 实例是 JobDetailID +“A”,并且当有多行具有相同的 JobDetailID 时,我希望连续的行是 JobDetailID +“B”、“C”等。具有相同 JobDetailID 的行不超过四五行。
我目前将其实现如下,但速度慢得令人无法接受:
private void AddCalculatedID(DataTable data)
{
var calculatedIDColumn = new DataColumn { DataType = typeof(string), ColumnName = "CalculatedID" };
data.Columns.Add(calculatedIDColumn);
data.Columns["CalculatedID"].SetOrdinal(0);
var enumerableData = data.AsEnumerable();
foreach (DataRow row in data.Rows)
{
var jobDetailID = row["JobDetailID"].ToString();
// Give calculated ID of JobDetailID + A, B, C, etc. for multiple rows with same JobDetailID
int x = 65; // ASCII value for A
string calculatedID = jobDetailID + (char)x;
while (string.IsNullOrEmpty(row["CalculatedID"].ToString()))
{
if ((enumerableData
.Any(r => r.Field<string>("CalculatedID") == calculatedID)))
{
calculatedID = jobDetailID + (char)x;
x++;
}
else
{
row["CalculatedID"] = calculatedID;
break;
}
}
}
}
假设我需要遵守这种输出格式,我该如何提高这种性能?