Disabling Case sensitivity for my keyword search [duplicate] - c#

This question already has answers here:
Case insensitive 'Contains(string)'
(29 answers)
Closed 5 years ago.
I have a filter by text search in my wpf application. However when I do a string comparison to check if it contains a buzzword like, oh say "error", I want it to update/refresh my datagrid with all entries that have the Error keyword; regardless if I typed Error, or error, or eRRor in my search box.
Here is my code:
public class Foo
{
private void GetFilteredResults(MessageDetails detail, FilterEventArgs e)
{
foreach (MessageValue value in detail.MessageValue)
{
if (value.Value.Contains(txtFilterValue.Text))
{
//Returns true...
}
}
//Otherwise false
}
}
The Messagedetails is a container class and holds all of the datagrid row values.
The MessageValue is a struct that holds the actual message value in an ObservableCollection
Finally, the txtFilterValue is the control name of the textbox I am using to for my word filter
What I want to do is setup something to where I remove case sensitivity in order to cache all entries that match my keyword, regardless of how I type it. How would I go about that?

Let's say there is a boolean property CaseSensitive identifying the search mode. Then you can use string.IndexOf to solve this by setting the StringComparison correctly:
StringComparison comparison = CaseSensitive ?
StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
if (value.Value.IndexOf(txtFilterValue.Text, comparison) >= 0)
{
//Returns true...
}
The whole query can be simply written with LINQ like
private void GetFilteredResults(MessageDetails detail, FilterEventArgs e)
{
bool comparison = CaseSensitive ?
StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
return detail.MessageValue.Any(v => v.Value.IndexOf(txtFilterValue.Text, comparison) >= 0);
}

Related

How to access property of a class whose name is in a variable [duplicate]

This question already has answers here:
How to get a property value based on the name
(8 answers)
Closed 3 years ago.
I have a class with is a collection of XPaths. I want to pass the name of the field and want to get the XPath for that field. The problem here is I have to store the passed value in a variable and putting an if condition to check for the corresponding XPath variable as shown below.
As of now, I am using the if condition and I can use switch condition as well but this solution is not feasible as the collection of XPath will grow and it will become unmanageable.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new Program().IReturnXpath("LastName"));
}
public string IReturnXpath(String nameOfField)
{
if (nameOfField.Equals("Lastname"))
return new XpathCollection().Lastname;
else if (nameOfField.Equals("Firstname"))
return new XpathCollection().Firstname;
else
return "Xpath not found";
}
class XpathCollection
{
public string Lastname = "xpath for lastname";
public string Firstname = "xpath for firstname";
}
}
Let me explain how Microsoft solved exact same problem.
System.Drawing.Color has many properties each reflecting a single color. Color also has a FromName method which allows you to find a color by string parameter. Almost exactly your problem.
As you can see in their, implementation, they create a Hashtable and by using reflection they fill it. Next time someone asks for a color they just lookup and return it. Put generation code in a static constructor and you are done.
https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/ColorConverter.cs,d06a69beb42834b2

Check IEnumerable<T> is filled with optional words not to count [duplicate]

This question already has answers here:
Check List<T> for duplications with optional words to exclude
(4 answers)
Closed 4 years ago.
I am trying to create extension isEmpty method which would check whether my IEnumerable contains at least one element. Returning either true/false.
I would like to also be able to exclude some specific items from check therefore it should be like this:
1st check: if list items count == 0 then return true
2nd check: If not list empty (count > 0) then check what elements are there. If i say for instance in parameter listSpecialItems that i want: string.empty, "whatever", "dd" then if list contains only those items it should still return true. Means listSpecialItems defines items as they would not exist (not counts).
This is so far what i did, however at the moment it only checks items count.
public static bool IsEmpty<T>(this IEnumerable<T> list, IEnumerable<T> listSpecialItems)
{
if (list is ICollection<T>) return ((ICollection<T>)list).Count == 0;
return !list.Any();
}
You can use Enumerable.All and Contains, no need for Count or cast:
public static bool IsEmpty<T>(this IEnumerable<T> list, IEnumerable<T> treatAsEmpty = null)
{
if (treatAsEmpty == null) treatAsEmpty = Enumerable.Empty<T>();
return list.All(treatAsEmpty.Contains);
}
this handles these edge cases correctly:
an empty list: returns true
an empty treatAsEmpty: returns false if the list isn't empty

Match characters of two strings [duplicate]

This question already has answers here:
How can I check if a string exists in another string
(10 answers)
Closed 4 years ago.
Suppose,i have two strings.NameIs and Nam.Now i can check if one string is as same as the other using :
If (string1 == string2)
But it won't work here as the strings are not the same.But a portion of it is same.What i am trying to achieve is to check if my main string has any portion of the string given...I came across String.StartWith and EndWith methods but there,i need to specify what the string might start or end with but i cannot as the strings can be anything(that's why at the beginning,i said "Suppose").
So my first question is how to achieve this ? I don't want any step=to=step instruction but atleast a little bit of direction :)
However,if i get past that,there's still a drawback and it is the Case-Sensitive issue.I've come across this but i can't seem to figure the required implementation of this in my case because i need to overcome the first issue first.
How should i achieve these ?
For ordinal comparison you can use
str1.Contains(str2);
If you need your comparison to be case-insensitive you can do
str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) >= 0;
Note that you can hide the latter in an extension method, like
static bool ContainsIgnoreCase(this string #this, string other)
=> #this.IndexOf(other, StringComparison.OrdinalIgnoreCase) >= 0;
Use String.Contains
if (stringValue.ToLower().Contains(anotherString.ToLower())) {
// Do Work //
}
Just remember to check that strings aren't null when doing contains comparing, or you will get an ArgumentNullException..
To check if substring is contained in main string, and to ignore case-sensitivity do this, its a boolean function that takes two string parameters:
public bool DoesStringExistInsideMainString(string mainString, string subString)
{
return mainString.ToLower().Contains(subString.ToLower());
}
Easiest way is this:
a = a?.ToLowerInvariant();
b = b?.ToLowerInvariant();
if(a==null || b==null || a.Contains(b) || b.Contains(a))
{
//do stuff
}
Why null propogates into true? Because if any variable is null it will definitly contains in other variable. The other two specs is just for non-null entries.

Checking value from Combobox(string) without ToString C#

I'm doing a project where "ToString" is being used as a method.
private void button1_Click(object sender, EventArgs e)
{
if(cboPlaneType.SelectedItem = "Generic")
{
}
else if (cboPlaneType.SelectedIndex = "Passenger")
{
}
else if (cboPlaneType.SelectedIndex = "Fighter Jet")
{
}
}
And in this case i'm not sure what to do. As you can see I've tried a few different option but with no avail. I've also tried
if((string)cboPlaneType.SelectedItem = "Generic")
And that didn't work.
**Edit
Just to point out, SelectedValue wasn't the correct answer.
ended up being "if((string)combobox.SelectedItem == "Generic")
The equality operator in c# is ==; = is an assignment operator.
SelectedIndex will return an int representing the zero-based position of the item that is selected. (I'm guessing it returns -1 when no item is selected.)
SelectedItem can be an object of any type; if it is not a string then you can't match it by comparing with a string.
Are you saying that the objects with which the ComboBox is populated override ToString()? You should still be able to use the result of that method for comparison, because it can only return a string. Otherwise, you might be able to use SelectedValue, but this depends on what kind of ComboBox you are using and how you have set it up.
SelectedIndex is an property of type Int32.
Maybe you want to use SelectedValue instead ?

Associating Strings with enums in C#

I work on C# window ...vs05 ......i want to put space on enum string ....i do it below code have this.....My problem is after select a value from the combo how can i get the index number of this value .....and if i gone to edit mode then i need to show the value what is user already selected .....how to get enum selected value on basis of index number
public enum States
{
California,
[Description("New Mexico")]
NewMexico,
[Description("New York")]
NewYork,
[Description("South Carolina")]
SouthCarolina,
Tennessee,
Washington
}
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
public static IEnumerable<T> EnumToList<T>()
{
Type enumType = typeof(T);
// Can't use generic type constraints on value types,
// so have to do check like this
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
foreach (int val in enumValArray)
{
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}
return enumValList;
}
private void Form1_Load(object sender, EventArgs e)
{
//cboSurveyRemarksType = new ComboBox();
cboSurveyRemarksType.Items.Clear();
foreach (States state in EnumToList<States>())
{
cboSurveyRemarksType.Items.Add(GetEnumDescription(state));
}
}
You could iterate through the enums available (Enum.GetValues(enumType)) and see which one has the description chosen (not the best performance but it is probably not significant for combo-boxes).
You could create your own attribute, and have the index there as well (ugly in terms of coding practice)
If you want to improve performance on option #1 you could pre-cache a Dictionary<String, Integer> object with the descriptions of each enum, and use that instead.
So you have an integer and you want to convert it back to the enum type? Just cast it. So long as you haven't explicitly specified any values in your enum declaration, and so long as the "index" you've got is 0-based you should be able to do:
States state = (States) stateIndex;
(Note that by normal .NET naming conventions this should be called State by the way - plurals are usually reserved for flags.)
This answer is based on the text of your question rather than your code - I can't see anything in your code which really refers to an index.
Simple. You can cast the selected index (which is an integer) to the States enum. I have written a simple test method which demonstrates a few examples of using the enum that should help clear the concept:
private static void TestMethod()
{
foreach (States state in EnumToList<States>())
{
Console.Write(GetEnumDescription(state) + "\t");
Int32 index = ((Int32)state);
Console.Write(index.ToString() + "\t");
States tempState = (States)index;
Console.WriteLine(tempState.ToString());
}
Console.ReadLine();
}
If you don't understand, would be happy to clarify further.

Categories

Resources