Reputation: 1
I have an array that I call from SQL and has , (commas) in it. I want to populate a excel with it. However, sometimes the array has no values, 1 value, 2 .....up to 5 values (i.e. , commas). So I am trying to separate it into a separate variable based on the length of the array.
string[] BeneficiaryFullName1 = ex.BeneficiaryFullName1.Split(' ');
if (BeneficiaryFullName1 != null ||
BeneficiaryFullName1.Length >= 0 &&
BeneficiaryFullName1.Length < 1)
{
ex.BeneficiaryFullName1 = BeneficiaryFullName1[0];
}
if (BeneficiaryFullName1 != null ||
BeneficiaryFullName1.Length >= 0 &&
BeneficiaryFullName1.Length < 2)
{
ex.BeneficiaryFullName1 = BeneficiaryFullName1[0];
ex.BeneficiaryFullName2 = BeneficiaryFullName1[1];
}
However, I am not getting it right. When there is "" empty return it keeps going to the second if statement and gives an error. What am I doing wrong?
Upvotes: 0
Views: 147
Reputation: 186728
Remove BeneficiaryFullName1 != null
(which is redundant) and BeneficiaryFullName1.Length < ...
(which is erroneous: if we have a name with, say, 4
words we can and should take first two of them):
// We want at most 3 items, empty ones (e.g. trailing spaces) removed
string[] BeneficiaryFullName1 = ex.BeneficiaryFullName1.Split(
' ', 3, StringSplitOptions.RemoveEmptyEntries);
// If we have at least 2 items, take the 2nd
if (BeneficiaryFullName1.Length >= 2)
ex.BeneficiaryFullName2 = BeneficiaryFullName1[1];
// If we have at least 1 item, take the 1st
if (BeneficiaryFullName1.Length >= 1)
Bex.BeneficiaryFullName2 = BeneficiaryFullName1[0];
Upvotes: 1