How to make the text case insensitive? - c#

Kindly suggest me a way to make the text case insensitive. The textbox input need to be compared irrespective of whatever case the user use
Example:
if (textBox1.Text == "Name")
{
label1.Content = "This is" + textBox1.Text;
}
If the textBox1 input is Name/ NAME/ name, the label should display the corresponding value.

I think you are looking for StringComparer.CurrentCultureIgnoreCase
if(string.Equals(textBox1.Text, "Name", StringComparer.CurrentCultureIgnoreCase))
You may also try to look at
System.Collections.CaseInsensitiveComparer

When comparing strings you really want to use the .Equals method
textBox1.Text.Equals("Name", StringComparison.CurrentCultureIgnoreCase);
The second parameter allows you to specify a StringComparison. In this example it tells it to ignore the case.

Can you please try the following:
if(textBox1.text.Equals("value",StringComparison.InvariantCultureIgnoreCase))
Hope this helps

Try This:
if(textBox1.Text.Equals("Name",StringComparision.InvariantCultureIgnoreCase))
{
label1.Content = "This is" + textBox1.Text;
}

simply you can use ToUpper or ToUpperInvariant
if (textBox1.Text.ToUpper() == "NAME")
if you need to uppercase using the casing rules of the invariant culture
if (textBox1.Text.ToUpperInvariant() == "NAME")

Try something like this
if (textBox1.Text.ToLowerInvariant() == "Name".ToLowerInvariant())
label1.Content = "This is" + textBox1.Text;

You can instantiate a comparer and reuse it throughout your code.
This Insensitive class provides a thorough set of insensitive comparison methods:
public static class Insensitive
{
private static IComparer m_Comparer = CaseInsensitiveComparer.Default;
public static IComparer Comparer
{
get{ return m_Comparer; }
}
public static int Compare( string a, string b )
{
return m_Comparer.Compare( a, b );
}
public static bool Equals( string a, string b )
{
if ( a == null && b == null )
return true;
else if ( a == null || b == null || a.Length != b.Length )
return false;
return ( m_Comparer.Compare( a, b ) == 0 );
}
public static bool StartsWith( string a, string b )
{
if ( a == null || b == null || a.Length < b.Length )
return false;
return ( m_Comparer.Compare( a.Substring( 0, b.Length ), b ) == 0 );
}
public static bool EndsWith( string a, string b )
{
if ( a == null || b == null || a.Length < b.Length )
return false;
return ( m_Comparer.Compare( a.Substring( a.Length - b.Length ), b ) == 0 );
}
public static bool Contains( string a, string b )
{
if ( a == null || b == null || a.Length < b.Length )
return false;
a = a.ToLower();
b = b.ToLower();
return ( a.IndexOf( b ) >= 0 );
}
}
Source: https://github.com/runuo/runuo/blob/master/Server/Insensitive.cs

Related

C# Implicit Operator not working with reflection

I am working on a requirement where in I need to check my ASP.NET Model Property for a value 000000.If the value is 000000 then it should be displayed as blank string.
I thought of achieving this using implicit operators.
Here is my model class
public class OrgName
{
private string Value { get; set; }
public static implicit operator string(OrgName org)
{
return org.Value;
}
public static implicit operator OrgName(string value)
{
bool isAllZeros = value.Where(x => char.IsDigit(x)).All(x => x == '0');
if (isAllZeros)
value = string.Empty;
return new OrgName() { Value = value };
}
}
The problem is that we are using reflection to set property values.The above code does not work and the property is always displayed as blank.
Here is the reflection code
var prName = (String.IsNullOrWhiteSpace(parentPrefix) ? objKey : parentPrefix + '.' + objKey);
var pi = modelMap[prName.ToLowerInvariant()].Property;
var value = (collectionProperties.ContainsKey(objKey)) ? collectionProperties[objKey] : pi.GetValue(parentObj);
if (value == null || pi.PropertyType.IsSimpleType())
{
value = (prName == fieldToSet && pi.PropertyType.IsSimpleType())
? (Convert.IsDBNull(valueToSet)) ? null : valueToSet
: createObject(pi.PropertyType);
var type = Nullable.GetUnderlyingType(pi.PropertyType);
//check to see if we need to convert the type when assigning
if (type == typeof(Guid))
value = Guid.Parse(value.ToString());
pi.SetValue(parentObj, type != null ? Convert.ChangeType(value, type) : value);
if (pi.PropertyType != typeof(string) && IsContainerProperty(pi.PropertyType))
continue;
if (pi.PropertyType == typeToReturn)
objToLoad = value;
}
else if (!collectionProperties.ContainsKey(objKey) && IsContainerProperty(pi.PropertyType))
{
var innerType = pi.PropertyType.GetGenericArguments()[0];
var add = pi.PropertyType.GetMethod("Add",
BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public);
if (innerType.IsSimpleType())
{
collectionProperties[objKey] = valueToSet;
add.Invoke(value, new[] { valueToSet });
}
else
{
// Since we can't access the property
var innerObj = createObject(innerType);
collectionProperties[objKey] = innerObj;
add.Invoke(value, new[] { innerObj });
if (innerType == typeToReturn)
objToLoad = innerObj;
continue;
}
}
Can someone help me out with this?
I am also open to other suggestions to achieve this.
Thanks
You could just put the code in the setter?
public class OrgName
{
private string _value;
private string Value
{
get { return _value; }
set
{
bool isAllZeros = value?.All(x => x == '0') ?? false;
if(isAllZeros)
{
_value = string.Empty;
}
else
{
_value = value;
}
}
}
}
This might be an indirect solution to your problem as right now your code has a flaw.
Ex. a0000a0b0 will be detected as isAllZeros
To explain any further what exactly the issue in your code is.
First let's look at this line:
bool isAllZeros = value.Where(x => char.IsDigit(x)).All(x => x == '0');
The first thing you do is taking value and performing a Where on it. The condition for the where to pass is that each value (x) is a digit. Which means that any non-digit characters such as a, b, c will be skipped.
As contrary to what you may have interpreted Where as then it just filters away any values that doesn't match the condition.
This means that values that aren't digits in your case will not pass and thus when the enumeration hits All then it will only enumerate the characters that are digits.
What your code is basically equivalent to in an English speaking is:
Take value
Skip all characters that aren't digits
Check if all digit characters are 0's
What you want your code to actually do is:
Take value
Check if all characters are digits and 0. In this case you actually only have to check if the character is '0'. The char.IsDigit check is redundant.
It could be solved by doing this:
bool isAllZeros = value.All(x => x == '0');
You might want to put in a null check in case value is null though.
bool isAllZeros = value?.All(x => x == '0') ?? false;
In case you aren't using C# 6
bool isAllZeros = string.IsNullOrEmpty(value) ? false : value.All(x => x == '0');

ASP.NET/C# - Find entry in an array and get it's index

I want to find a particular Textbox in an array of Textboxes, and return it's index.
This line finds the relevant control:
TextBox tb1 = Array.Find(m_dynamicTextBoxes, element => element.ID == strFieldId);
I want to find it's index, ao that I can replace this control with a similar one. An error has been detected, so I plan to change the BorderColor to Red.
Use Array.FindIndex
var index = Array.FindIndex(m_dynamicTextBoxes, element => element.ID == strFieldId);
If you just want to change the BackColor then you can use your query and change the Color on your found TextBox
tb1.BackColor = Color.Red;
Simple LINQ extensions:
public static class LinqExtensions
{
public static int? IndexOfOrNull<T>( this IEnumerable<T> list , Func<T,bool> isDesired )
{
int i = 0 ;
bool desired = false ;
foreach ( T item in list )
{
desired = isDesired(item) ;
if ( desired ) break ;
++i ;
}
return desired ? i : (int?)null ;
}
public static int IndexOf<T>( this IEnumerable<T> list , Func<T,bool> isDesired )
{
int? index = IndexOfOrNull( list , isDesired ) ;
if ( !index.HasValue ) throw new InvalidOperationException() ;
return index.Value ;
}
}
Or you could write a similar extension to do the in-place replacement and return the replaced item:
public static T Replace<T>( this T[] list , Func<T,bool> isDesired , T replacement ) where T:class
{
T replacedItem = null ;
for ( int i = 0 ; replacedItem == null && i < list.Length ; ++i )
{
T item = list[i] ;
bool desired = isDesired(item) ;
if ( desired )
{
replacedItem = item ;
list[i] = replacement ;
}
}
return replacedItem ; // the replaced item or null if no replacements were made.
}

Library with Equals and GetHashCode helper methods for .NET

Google Guava provides nice helpers to implement equals and hashCode like the following example demonstrates:
public int hashCode() {
return Objects.hashCode(lastName, firstName, gender);
}
Is there a similar library for Microsoft .NET?
I don't see why you'd need one. If you want to create a hash-code based on the default GetHashCode for 3 different items, then just use:
Tuple.Create(lastName, firstName, gender).GetHashCode()
That'll boil down to the equivalent of:
int h1 = lastName.GetHashCode();
int h2 = firstName.GetHashCode();
int h3 = gender.GetHashCode();
return (((h1 << 5) + h1) ^ (((h2 << 5) + h2) ^ h3));
Which is pretty reasonable for such a general-purpose combination.
Likewise:
Tuple.Create(lastName, firstName, gender).Equals(Tuple.Create(lastName2, firstName2, gender2))
Would boil down to the equivalent of calling:
return ((lastName == null && lastName2 == null) || (lastName != null && lastName.Equals(lastName2)))
&& ((firstName == null && firstName2 == null) || (firstName != null && firstName.Equals(lastName2)))
&& ((gender == null && gender2 == null) || (gender != null && gender.Equals(lastName2)));
Again, about as good as you could expect.
AFAIK none. However, writing your own shouldn't be too complex (nb using a variation of the Bernstein hash):
public static class Objects
{
public static bool Equals<T>(T item1, T item2, Func<T, IEnumerable<object>> selector)
{
if (object.ReferenceEquals(item1, item2) return true;
if (item1 == null || item2 == null) return false;
using (var iterator1 = selector(item1).GetEnumerator())
using (var iterator2 = selector(item2).GetEnumerator())
{
var moved1 = iterator1.MoveNext();
var moved2 = iterator2.MoveNext();
if (moved1 != moved2) return false;
if (moved1 && moved2)
{
if (!Equals(iterator1.Current, iterator2.Current)) return false;
}
}
return true;
}
public static bool Equals(object item1, object item2)
{
return object.Equals(item1, item2);
}
public static int GetHashCode(params object[] objects)
{
unchecked
{
int hash = 17;
foreach (var item in objects)
{
hash = hash * 31 + item.GetHashCode();
}
return hash;
}
}
}

Is this possible somehow in C# : if (a==b==c==d) {...}

Is there a quick way to compare equality of more than one values in C#?
something like:
if (5==6==2==2){
//do something
}
Thanks
if (a == b && b == c && c == d) {
// do something
}
In C#, an equality operator (==) evaluates to a bool so 5 == 6 evaluates to false.
The comparison 5 == 6 == 2 == 2 would translate to
(((5 == 6) == 2) == 2)
which evaluates to
((false == 2) == 2)
which would try to compare a boolwith an int. Only if you would compare boolean values this way would the syntax be valid, but probably not do what you want.
The way to do multiple comparison is what #Joachim Sauer suggested:
a == b && b == c && c == d
public static class Common {
public static bool AllAreEqual<T>(params T[] args)
{
if (args != null && args.Length > 1)
{
for (int i = 1; i < args.Length; i++)
{
if (args[i] != args[i - 1]) return false;
}
}
return true;
}
}
...
if (Common.AllAreEqual<int>(a, b, c, d, e, f, g))
This could help :)
No this is not possible, you have to split it into separate statements.
if(x == y && x == z) // now y == z
{
}
Good luck

Determine value of object in C#

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

Categories

Resources