I have the following line of code:
List<int> _people = code.data.loadScalarDataPoint(code.enums.pathNames.Department, "Department_Staff", RecId).Split('|').Select(int.Parse).ToList();
The static method loadScalarDataPoint
returns a string of the selected column for given inputs.
In this instance, it returns a list of pipe delimited integers (eg 12|45|88|1543|123
) or if the column is NULL
it will return an empty string.
Using the linq Select(int.Parse)
works if there is a result but without it throws the following error " Input string was not in a correct format "
I know why, as you can't parse an empty string into a int
, however is there a way within the single line of code to check for this?
Or do I need to get the result into a string, check if it has contents and if so parse into a list of int
s?
EDIT with full explanation: In your failing case, the loadScalarDataPoint
method returns an empty string, which the call to Split(',')
returns an IEnumerable<String>
with one empty string in it. The call to Select(Int32.Parse)
throws an exception because an empty string is not in the correct format.
Use
.Split(new [] {'|'}, StringSplitOptions.RemoveEmptyEntries)
为什么不先检查非空结果?
List<int> _people = code.data.loadScalarDataPoint(code.enums.pathNames.Department, "Department_Staff", RecId).Split('|').Where(a => a.Any()).Select(int.Parse).ToList();
Add the following before the select:
.Where(x=>!string.IsNullOrEmpty(x))
This basically ensures that when doing the select there are only elements that have a string value.
Be aware you will need to handle the empty case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.