How can i check if filename contains some string? for example if "frody" contains "ro"?
I tried like that:
if (file_name.Contains("ro")== true)
and:
if (file_name.Contains("ro"))
Both are correct. The second is probably more favoured.
E.g., this returns true:
string s = "test-ro.doc";
Console.WriteLine(s.Contains("ro"));
if (s == null || s.Trim().Length == 0)
{
return false
}
else
{
return s.ToLower().Contains("ro");
}
Related
I am adding validation to my text string. It allows string and integer values, which is correct, but I want to require my text to be greater than 4 characters long. I've added the text.Length > 4 but this does not add any validation when entering a 2 character string. Any suggestions?
public bool IsStringInvalid(string text)
{
if (String.IsNullOrEmpty(text))
{
if (text != null && !Regex.IsMatch(text, textCodeFormat) && text.Length > 4)
{
return true;
}
}
return false;
}
Your method is called IsStringLengthInvalid, which implies that it should be returning true for invalid strings. Right now, it appears you're trying to return true only for valid strings.
Something like this should work:
public bool IsStringInvalid(string text)
{
return string.IsNullOrEmpty(text) ||
text.Length <= 4 ||
!Regex.IsMatch(text, textCodeFormat);
}
You are checking for not null condition nested inside the null condition which is logically wrong. You should do something like this.
public bool IsStringInvalid(string text)
{
if (text != null && text.Length > 4 && !Regex.IsMatch(text, textCodeFormat))
{
return true;
}
return false;
}
You have your length validation if statement nested inside your other if. If text has any data if will never reach the nested if as it will fail the first since IsNullOrEmpty will return false.
I would do something like
if (String.IsNullOrEmpty(text) || !Regex.IsMatch(text, textCodeFormat) || text.Length < 4)
{
return true;
}
return false;
I have created a simple Code using if else clause,it throws error like expected ";". But when I check the code everything seems correct. I am new to C# coding.
public string empstatus(string trmdate, string status)
{
if( trmdate!= NULL)
{
if(status = "RETIREE")
{
return "RT";
}
else retun "FT";
}
else return "TF";
}
This compiles:
public string empstatus(string trmdate, string status)
{
if( trmdate!= null)
{
if(status == "RETIREE")
{
return "RT";
}
else return "FT";
}
else
return "TF";
}
Mistakes:
retun instead of return
if(status = "RETIREE") instead of if(status == "RETIREE")
NULL instead of null
if(status = "RETIREE") should be if(status == "RETIREE")
Also consider checking status for Null.
Please read about c# operators - https://msdn.microsoft.com/en-us/library/6a71f45d.aspx
You should compare 2 objects by using '==' operator.
if (status == "RETIREE")
explicit equasion == in c# is used to test the value of variable, while equasion = is used for value assignment
I have string with empty space("________")
string MyNote= Convert.ToString(Session["MyNote"]);
if(MyNote!=null || MyNote != "")
{
}
MyNote != "" does not work if string has more space so
How can I check my string is "" or null by using linq in C#?
String.IsNullOrWhiteSpace is the method you're looking for.
Indicates whether a specified string is null, empty, or consists only of white-space characters.
Alternatively, using your idea:
if(MyNote!=null && MyNote.Trim() != "")
{
}
or
if(MyNote!=null && MyNote.Trim().Length == 0)
{
}
if(MyNote!=null || MyNote.Length > 0) //or you may want to set different value than 0
{
}
This works for me:
string MyNote = Session["MyNote"] == null ? String.Empty : Session["MyNote"].ToString();
I have the following code on an asp.net button click
if(str == ipaddr1 || ipaddr2 || ipaddr3 || ipaddr4 || ipaddr5 || ipaddr6 || ipaddr7)
// do this
else
//cancel click event
How can I optimize this piece of code?
Update: Apologies everyone! I did not mean to compare it with the literal string ipaddr. I mean to compare it to the value ipaddr1, ipaddr2 holds and so on
replace with:
Regex.IsMatch(str, "^ipaddr[1-7]$")
Optimised for readability not necessarily performance.
HashSet<T> is the best container to check containing:
var ips = new HashSet<string> { "ip1", "ip2", "ip3", "ip4", "ip5" };
if (ips.Contains(input))
{
// do stuff
}
For any type:
var ips = new HashSet<IPHostEntry> { ip1, ip2, ip3, ip4, ip5 };
if (ips.Contains(input))
{
// do stuff
}
Was:
if(str = qry.StartsWith("23.55") || str = qry.StartsWith("xuz") || str = qry.StartsWith("i3") || str = qry.StartsWith("i444") || str = qry.StartsWith("ki5") || str = qry.StartsWith("65fr6")) // do this else // do this
Become:
var arr = new[] { "23.55", "xuz", "i3", "i444", "ki5", "65fr6") };
if (arr.Any(str => input.StartsWith(str, StringComparison.Ordinal))
{
// do stuff
}
StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase are very important for performance.
What about
if(str.Substring(0,6) == "ipaddr" && str[6] >= '1' && str[6] <= '7')
For your information, your original code does not even compile. This
if(str == "ipaddr1" || "ipaddr2" || "ipaddr3" || "ipaddr4" || "ipaddr5" || "ipaddr6" || "ipaddr7")
Needs to be replaced with this to compile
if(str == "ipaddr1" || str == "ipaddr2" || str == "ipaddr3" || str == "ipaddr4" || str == "ipaddr5" || str == "ipaddr6" || str == "ipaddr7")
So the original code is actually even more tedious than you thought.
UPDATE
According to your updated question, the best option is to put your string variables into a List<string> called, for example ipaddr. Then to see if the string str is included, simply do this:
if( ipaddr.Contains( str ) )
{
//contained in the list
}
I would do something like:
str.Length == 7 && str.StartsWith("ipaddr") && str[6] > '0' && str[6] < '8'
Edit:
After your update, I would do something like:
string[] validStrings = { ipaddr1, ipaddr2, ... };
bool isStrValid = validStrings.Contains(str);
For better performance, consider using a HashSet<string> instead of an array, especially if the list of valid strings doesn't change.
Both more readable, and more performant would be:
switch(str)
{
case "ipaddr1":
case "ipaddr2":
case "ipaddr3":
case "ipaddr4":
case "ipaddr5":
case "ipaddr6":
case "ipaddr7":
//do something
break;
default:
//do something else
break;
}
(although, admittedly massively verbose...)
I would do a
List<string> variables = new List<string> { "ip1","ip2","ip3","ip4","ip5" };
if (variables.Contains(inputstring))
...
What would be the best way to determine if an object equals number zero (0) or string.empty in C#?
EDIT: The object can equal any built-in System.Value type or reference type.
Source Code:
public void MyMethod(object input1, object input2)
{
bool result = false;
object compare = new object();
if(input != null && input2 != null)
{
if(input1 is IComparable && input2 is IComparable)
{
//do check for zero or string.empty
//if input1 equals to zero or string.empty
result = object.Equals(input2);
//if input1 not equals to zero or string.empty
result = object.Equals(input1) && object.Equals(input2); //yes not valid, but this is what I want to accomplish
}
}
}
Using Jonathan Holland code sample with a minor modification, here is the solution that worked:
static bool IsZeroOrEmpty(object o1)
{
bool Passed = false;
object ZeroValue = 0;
if(o1 != null)
{
if(o1.GetType().IsValueType)
{
Passed = (o1 as System.ValueType).Equals(Convert.ChangeType(ZeroValue, o1.GetType()))
}
else
{
if (o1.GetType() == typeof(String))
{
Passed = o1.Equals(String.Empty);
}
}
}
return Passed;
}
What's wrong with this?
public static bool IsZeroOrEmptyString(object obj)
{
if (obj == null)
return false;
else if (obj.Equals(0) || obj.Equals(""))
return true;
else
return false;
}
Michael, you need to provide a little bit more information here.
strings can be compared to null or string.Empty by using the method
string x = "Some String"
if( string.IsNullOrEmpty(string input) ) { ... }
int, decimals, doubles (and other numeric value-types) can be compared to 0 (zero) with a simple == test
int x = 0;
if(x == 0) { ... }
You can also have nullable value-types also by using the ? operator when you instantiate them. This allows you to set a value type as null.
int? x = null;
if( !x.HasValue ) { }
For any other object, a simple == null test will tell you if its null or not
object o = new object();
if( o != null ) { ... }
Hope that sheds some light on things.
Not quite sure the reasoning behind this, because .Equals is reference equality on reference types, and value equality on value types.
This seems to work, but I doubt its what you want:
static bool IsZeroOrEmpty(object o1)
{
if (o1 == null)
return false;
if (o1.GetType().IsValueType)
{
return (o1 as System.ValueType).Equals(0);
}
else
{
if (o1.GetType() == typeof(String))
{
return o1.Equals(String.Empty);
}
return o1.Equals(0);
}
}
Do you mean null or string.empty, if you're talking about strings?
if (String.IsNullOrEmpty(obj as string)) { ... do something }
Oisin
In the first case by testing if it is null. In the second case by testing if it is string.empty (you answered your own question).
I should add that an object can never be equal to 0. An object variable can have a null reference though (in reality that means the variable has the value of 0; there is no object in this case though)
obj => obj is int && (int)obj == 0 || obj is string && (string)obj == string.Empty