string sql = string.Format(@"SELECT DISTINCT TenantId , TenantName FROM {0} ORDER BY TenantId", biao); var dataTable = _sqlSugarClient.Ado.GetDataTable(sql); // 将 DataTable 转换为 List<string> List<string> stringList = dataTable.AsEnumerable().Select(row => row.Field<string>(0) + "|" + row.Field<string>(1)).ToList(); // 将 List 分别赋值给 key 和 value 字段 List<KeyValue> keyValueList = new List<KeyValue>(); foreach (string str in stringList) { string[] strArray = str.Split('|'); KeyValue keyValue = new KeyValue(); keyValue.key = strArray[0]; keyValue.value = strArray[1]; keyValueList.Add(keyValue); }报错System.InvalidCastException:“Unable to cast object of type 'System.Int64' to type 'System.Int32'.”
时间: 2023-12-17 15:05:44 浏览: 149
这个错误是因为您在使用 `row.Field<string>(0)` 时,`0` 应该是 `Int32` 类型的,但是实际上返回的类型是 `Int64`,因此无法转换成 `Int32` 类型。您可以尝试在 `Select` 语句中将返回的列转换成 `Int32` 类型,例如:
```
string sql = string.Format(@"SELECT DISTINCT CONVERT(INT, TenantId) AS TenantId, TenantName FROM {0} ORDER BY TenantId", biao);
var dataTable = _sqlSugarClient.Ado.GetDataTable(sql);
List<string> stringList = dataTable.AsEnumerable().Select(row => row.Field<string>(0) + "|" + row.Field<string>(1)).ToList();
List<KeyValue> keyValueList = new List<KeyValue>();
foreach (string str in stringList)
{
string[] strArray = str.Split('|');
KeyValue keyValue = new KeyValue();
keyValue.key = strArray[0];
keyValue.value = strArray[1];
keyValueList.Add(keyValue);
}
```
这里使用了 `CONVERT(INT, TenantId)` 将返回的 `TenantId` 列转换成 `Int32` 类型。
阅读全文