Linq or string filter - c#

I need a filter on the string which takes another string as a parameter, scans first string and removes all appearances of it.

You can use string.Replace which has an overload specifically for this.
var newString = oldString.Replace("foo", string.Empty);
This takes your oldString, finds all occurrences of "foo" and removes them.

This would work
var s = "string";
s = s.Replace("st", string.Empty);
// s == "ring";
Is that not correct?

Use extension methods:
public static class StringExtensions
{
public static string RemoveOccurences(this string s, string occurence)
{
return s.Replace(occurence, "");
}
}
usage:
string s = "Remove all appearances of this and that and those";
s.RemoveOccurences("th");

Related

Delete a string variable from Another String Variable in C#

I have a string variable operation_sequence. I'd like to remove another string variable job.Description from it.
For example, if I wanted to add job.Description to operation_sequence, I can do:
operation_sequence += job.Description;
and this works. But if I wanted to remove job.Description from operation_sequence, the following code does not work:
operation_sequence -= job.Description;
What's the best way to remove job.Description from operation_sequence?
You could easily use String.Replace():
String HelloWord = "Hello World!";
String NewWord= HelloWord.Replace("o","");
NewWord will be=Hell Wrld!
We can't use -= or - for string. But we can implement it for our own string class.
Solution 1
public class MyString
{
public string Value { get; private set; }
public MyString(string value)
{
Value = value;
}
public static MyString operator +(MyString left, MyString right)
{
return new MyString(left.Value + right.Value);
}
public static MyString operator -(MyString left, MyString right)
{
if (string.IsNullOrEmpty(left.Value))
return left;
if (string.IsNullOrEmpty(right.Value))
return left;
if (left.Value.EndsWith(right.Value))
{
int startIndex = left.Value.Length - right.Value.Length;
string result = left.Value.Substring(0, startIndex);
return new MyString(result);
}
return left;
}
public static implicit operator string(MyString value) => value.Value;
public static implicit operator MyString(string value) => new MyString(value);
}
As you know we can't overload -= and +=(See this). Therefore I overloaded - and +. Now we can use our class like this:
MyString s1 = "This is ";
MyString s2 = "just a test";
string s3 = s1 + s2; // s3 = "This is just a test"
string s4 = s3 - s2; // s4 = "This is "
Because of public static implicit operator MyString(string value) => new MyString(value) we can have something like MyString s1 = "test". It implicitly converts string to MyString.
Because of public static implicit operator string(MyString value) => value.Value we can have something like string s3 = MyString("test"). It implicitly converts MyString to string.
In the - operator we checked if the left operand ends with the right one, we removed it.
Solution 2
And also we can simply use an extension method like this:
public static class StringExtension
{
public static string MinusString(this string baseString, string minusString)
{
if (string.IsNullOrEmpty(baseString))
return baseString;
if (string.IsNullOrEmpty(minusString))
return baseString;
if (baseString.EndsWith(minusString))
{
int startIndex = baseString.Length - minusString.Length;
string result = baseString.Substring(0, startIndex);
return new MyString(result);
}
return baseString;
}
}
and now we can use it like this:
string s = "This is just a test";
string s3 = s.MinusString("a test"); // s3 = "This is just "
s3 = s3.MinusString("just "); // s3 = "This is "
Solution suggested by Klaus Gütter worked for me, which is defining operation_sequence as a List and converting it to a string only after manipulation, using String.Join.
private string operation_sequence;
List<string> ops = new List<string>(3);
// Add item to List:
ops.Add(job.Description);
// or Remove item from List:
ops.Remove(job.Description);
//then update operation_sequence string with values from List<string>:
operation_sequence = String.Join(", ", ops);

Regex combine more than 1 function

How can I call 2 functions in my code for one string?
public static string ecleaner(string str)
{
return Regex.Replace(str, "[éèê]+", "e", RegexOptions.Compiled);
}
public static string acleaner(string str)
{
return Regex.Replace(str, "[áàâ]+", "a", RegexOptions.Compiled);
}
Now I want to check the word "Téèááést" ,after this it should look like Teaest .
You could use a MatchEvaluator delegate, like this:
public static string cleaner(string str)
{
return Regex.Replace(str, "(?<a>[áàâ]+)|(?<e>[éèê]+)", onMatch, RegexOptions.Compiled);
}
private static string onMatch(Match m)
{
if (m.Groups["a"].Success)
return "a";
if (m.Groups["e"].Success)
return "e";
return "";
}
Or alternatively:
public static string cleaner(string str)
{
var groups = new[] { "a", "e" };
return Regex.Replace(str, "(?<a>[áàâ]+)|(?<e>[éèê]+)", m => groups.First(g => m.Groups[g].Success), RegexOptions.Compiled);
}
Did you try this?
string str = "Téèááést";
str = ecleaner(str);
str = acleaner(str);
public static class StringExtensions
{
public static string ecleaner(this string str)
{
return Regex.Replace(str, "[éèê]+", "e", RegexOptions.Compiled);
}
public static string acleaner(this string str)
{
return Regex.Replace(str, "[áàâ]+", "a", RegexOptions.Compiled);
}
}
//...
var result = "Téèááést".ecleaner().acleaner();
You could also combine an extension method class with #p.s.w.g's answer, to make things even neater.

Get argument value from string input

How do I create a class method to get the argument from a string input?
string value GetArugmentValueByName (string input, string name)
Example
myInput="code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp6&
client_id=21302922996.apps.googleusercontent.com&
client_secret=XTHhXh1SlUNgvyWGwDk1EjXB&
redirect_uri=https://www.example.com/back&
grant_type=authorization_code";
If I do this
string myGrantType = GetArugmentValueByName(myInput, "grant_type");
the value of myGrantType should equal "authorization_code"
You can use ParseQueryString to parse out the params into a name value collection, then index into that for the param you are looking for.
public string GetArgumentValueByName(string queryString, string paramName)
{
var paramCol = HttpUtility.ParseQueryString(queryString);
return paramCol[paramName] ?? string.Empty;
}

How to get the values of the parameters in a method with Reflection?

Using MethodBase, is it possible to get the parameters and their values of the method that's being called?
To be specific, I'm trying to use reflection to create Cache keys. As each method and its parameter list is unique, I thought it'd be ideal to use this as the key. This is what I'm doing:
public List<Company> GetCompanies(string city)
{
string key = GetCacheKey();
var companies = _cachingService.GetCacheItem(key);
if (null == company)
{
companies = _companyRepository.GetCompaniesByCity(city);
AddCacheItem(key, companies);
}
return (List<Company>)companies;
}
public List<Company> GetCompanies(string city, int size)
{
string key = GetCacheKey();
var companies = _cachingService.GetCacheItem(key);
if (null == company)
{
companies = _companyRepository.GetCompaniesByCityAndSize(city, size);
AddCacheItem(key, companies);
}
return (List<Company>)companies;
}
Where GetCacheKey() is defined (roughly) as:
public string GetCacheKey()
{
StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
string name = methodBase.DeclaringType.FullName;
// get values of each parameter and append to a string
string parameterVals = // How can I get the param values?
return name + parameterVals;
}
Why do you want to use reflection? In the place where you use your GetCacheKey method you know the values of the parameters. You can just specify them:
public string GetCacheKey(params object[] parameters)
And use like this:
public List<Company> GetCompanies(string city)
{
string key = GetCacheKey(city);
...
this is a great sample for getting parameters from a method:
public static string GetParamName(System.Reflection.MethodInfo method, int index)
{
string retVal = string.Empty;
if (method != null && method.GetParameters().Length > index)
retVal = method.GetParameters()[index].Name;
return retVal;
}
Looking for the same answer right. Besides reflection you can write an Aspect in PostSharp. This will cut any performance impact of using reflection and won't violate any substitution principles.

How to convert string type to user defined custom type

I have a string value that needs to be converted into my user defined custom type. how to do this, please help me.
public class ItemMaster
{
public static ItemMaster loadFromReader(string oReader)
{
return oReader;//here i am unable to convert into ItemMaster type
}
}
Depending on your type there are two ways that you could do it.
The first is adding a constructor to your type that takes a String parameter.
public YourCustomType(string data) {
// use data to populate the fields of your object
}
The second is adding a static Parse method.
public static YourCustomType Parse(string input) {
// parse the string into the parameters you need
return new YourCustomType(some, parameters);
}
Convert.ChangeType() method may help you.
string sAge = "23";
int iAge = (int)Convert.ChangeType(sAge, typeof(int));
string sDate = "01.01.2010";
DateTime dDate = (DateTime)Convert.ChangeType(sDate, typeof(DateTime));
Create a Parse method on your User Defined Custom type:
public class MyCustomType
{
public int A { get; private set; }
public int B { get; private set; }
public static MyCustomType Parse(string s)
{
// Manipulate s and construct a new instance of MyCustomType
var vals = s.Split(new char[] { '|' })
.Select(i => int.Parse(i))
.ToArray();
if(vals.Length != 2)
throw new FormatException("Invalid format.");
return new MyCustomType { A = vals[0], B = vals[1] };
}
}
Granted, the example provided is extremely simple but it at least will get you started.
First you need to define a format that your type will follow when being converted to a string.
A simple example is a social security number. You can easily describe it as a regular expression.
\d{3}-\d{2}-\d{4}
After that you simple need to reverse the process. The convention is to define a Parse method and a TryParse method for your type. The difference being that TryParse will not throw an exception.
public static SSN Parse(string input)
public static bool TryParse(string input, out SSN result)
Now the process you follow to actually parse the input string can be as complex or as simple as you wish. Typically you would tokenize the input string and perform syntactic validation. (EX: Can a dash go here?)
number
dash
number
dash
number
It really depends on how much work you want to put into it. Here is a basic example of how you might tokenize a string.
private static IEnumerable<Token> Tokenize(string input)
{
var startIndex = 0;
var endIndex = 0;
while (endIndex < input.Length)
{
if (char.IsDigit(input[endIndex]))
{
while (char.IsDigit(input[++endIndex]));
var value = input.SubString(startIndex, endIndex - startIndex);
yield return new Token(value, TokenType.Number);
}
else if (input[endIndex] == '-')
{
yield return new Token("-", TokenType.Dash);
}
else
{
yield return new Token(input[endIndex].ToString(), TokenType.Error);
}
startIndex = ++endIndex;
}
}
For the actual conversion, we would need to see the class structure for. The skeleton for this would look as follows however:
class MyType
{
// Implementation ...
public MyType ConvertFromString(string value)
{
// Convert this from the string into your type
}
}

Categories