Assign value if string is whitespace? [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a SQL command in C# that gets the manager field from a database like such:
SELECT manager FROM table WHERE number = '123456'
I then add it to a list like such:
c.Manager = Convert.ToString(sdr["manager"]);
I eventually add the result to a table. My problem is that in the database sometimes there is no entry for the number does not exist or the manager is just a string of whitespace.
How could assign the value " - " to c.Manager in these cases?

You could test for the value to see whether it's null or whitespace.
There's a handy built-in method in the String class:
var manager = Convert.ToString(sdr["manager"]);
c.Manager = string.IsNullOrWhiteSpace(manager) ? "-" : manager;

c.Manager = Convert.ToString(sdr["manager"])==""?"-":Convert.ToString(sdr["manager"]);

You could do a single line if statement
c.Manager = (Convert.ToString(sdr[#manager#]) == "") ? "-" : Convert.ToString(sdr["manager"]);

How about you tell your SQL script to return '-' instead of a whitespace or Null?
SELECT
CASE WHEN manager IS NULL
OR LTRIM(RTRIM(manager)) = ''
THEN '-'
ELSE manager
END AS manager
FROM table
WHERE number = '123456'
Benefit - Avoids data manipulation in C# code. Also keeps further changes easier and you can now simply assign the value to c .Manager.
NOTE - I firmly believe that if any data manipulation like the one in your case needs to be done, should be done while generating the resultset for better maintenance sake at least.

Related

Index and length must refer to a location with the string. Parameter name: length error [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
My program has been receiving this error recently and I am not sure why. The code that is triggering it is:
foreach (var lot in item.LotNum.Split('|'))
{
string vendor = string.Empty;
if (lot.Trim().Contains("-"))
vendor = lot.Trim().Substring(0, item.LotNum.IndexOf("-"));
}
LotNum = "br549 | BR549 | 570-PRIOR" and lot is "570-PRIOR" (without quotes) when the error triggers. I've not used IndexOf before and so I am not sure what is wrong with the string that is being sent in. I want to check for what causes the error beforehand because the exception is stopping the program and the bad data will be there for a while until it is fixed, and more may be added in the future.
Any help would be appreciated!
New answer according your code update:
var lots = item.LotNum.Split('|');
foreach (var lot in lots)
{
string vendor = string.Empty;
if (lot.Contains("-"))
vendor = lot.Substring(0, lot.IndexOf("-")).Trim();
}
Again, you were using IndexOf for a variable different than the one you want to get a substring
You are using IndexOf for a variable different than the one you want to get a substring, so, the index will be out of range.
Try with: edited
variable = variable.Trim();
int index = variable.IndexOf("-");
if (index > 0)
variable.Substring(0, index);
Another way to do this is to check for the existence of the character using Contains, and if it's found use the IndexOf, otherwise just use the Length of the string (and put Trim at the end to avoid issues with using the Length after trimming):
variable.Substring(0, variable.Contains('-')
? variable.IndexOf('-')
: variable.Length)
.Trim();

How to avoid this kind of exception? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have an sqlite database, and a table, in which i have a column PIN as a TEXT, and it's empty.
when i'm getting it from the database, and trying to convert into a string it brings me an exception, When casting a number the value must be less then infinity...what is the reason?
In databases like sqlite, empty strings and null are two different things. It looks like you may be trying to cast your PIN to an int, or some other integer type. If the PIN field is null or DBNull, this cast will fail, giving the exception you listed. To further complicate things, null != DBNull.Value, which is what your database query is likely returning.
To check for this, you need to check the PIN field against DBNull.Value and cast only after you've checked.
See: DBNull Class
See: A similar SO question

Find a specific number in the middle of a string and remove it from list of numbers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I don't have much code to show but I am trying to remove a substring (individual number) from a longer string is a series of numbers.
Ex: Main String is "11,12,15,16,55,33,88,100,121,155,115"
Need to find number 16 and remove it from the string leaving...
11,12,15,55,33,88,100,121,155,115
They are a list of id's from a database so I can't just change them to strings. Also how do I remove it as if it wasn't there?
string numbers = "11,12,15,16,55,33,88,100,121,155,115";
numbers = string.Join(",", numbers.Split(',').Where(num => num != "16"));
But why don't you use a List<int> instead for database ID's?
In this specific use case I would split the string using "," as the separator, remove the element that matches, then join the elements again.

I need to convert a bit[] into an [] of strings that represent each bit in the bit[] [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I'm working on an automated follow up system on highly antiquated techniques of registering the current status of a "Project" the GUI interaction in this system uses what are named "flags" that the user can "check" to designate the current status of a project. There are 11 possible boxes that can be checked and the system accepts multiple selections.
For example a user can select a check-box labeled "Confirmed" and or "Needs Follow Up" and or or "Is Scheduled" and or "Spoken with client" (There are 11 possible selections).
Here is the problem - whoever wrote this saved those selections to the database in a "bit sum" so the what you see is an int of the original bit[] for the check-box selections.
What I need to do is read the integer from the database and turn it back into a bit array of 11 values of 1 || 0 then from that bit array i need to determine which boxes of string value are checked in order to determine weather or not i need to perform an automated follow up.
So basically if "Confirmed" is checked i don't want to follow up
If "Needs-followup" is checked i need to follow up.
The problem here is that multiple selections can be present.
So after the int is turned into a bit[] we have for example
1,0,1,0,0,0,1,1,1,0,1 where each int represents a box checked.
i need to find a way to turn the above into an array of strings representing the box labels to determine which boxes are checked.
The usual way to do this in C# would be to use a flags enumeration - this is exactly what your bit field is.
[Flags]
enum ProjectStatus
{
Confirmed = 1,
NeedsFollowUp = 2,
SpokenWithClient = 4,
....
}
To test if a specific flag is set:
ProjectStatus status = (ProjectStatus)intFromDb;
if( ( status & ProjectStatus.Confirmed ) == ProjectStatus.Confirmed )
// the Confirmed flag is set
There is also a Enum.HasFlags extension method that simplifies this if you are in .NET 4 or higher.
If you do not wish to do it this way, you can find out if the bit at position x is set by doing this:
bool isSet = ( intFromDb & ( 1 << x ) ) != 0;
And use that to build your string.
Edit: I'd also suggest you read up a bit on bitwise operators and what they do. This might be a good start: http://blackwasp.co.uk/CSharpLogicalBitwiseOps.aspx

Does string.Replace("a", "b") automatically check if "a" exists? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
string banana = "banana apple";
banana.Replace("apple", "pie");
If I want to replace apple with pie, can I do it like that, or do I need to use the following?
if(banana.Contains("apple"))
banana.Replace("apple", "pie");
You just have to read msdn: ( or try it out yourself )
Return Value Type: System.String A string that is equivalent to the
current string except that all instances of oldValue are replaced with
newValue. If oldValue is not found in the current instance, the method
returns the current instance unchanged.
Side-note: since strings are immutable(you cannot change the instance) you have to reassign a new string if you want to change the old:
banana = banana.Replace("apple", "pie");

Categories

Resources