Using Contains Method to separate comma delimited string of numbers - c#

I have an IF statement as follows:
if (snumber == "9999-999-9999" && cnumber == "999")
{
// 30 Day Trial Demo Key
return "Good";
}
There's a serial number linked to one or multiple cnumbers. In some cases I have a list of 5-20 cnumbers seperated by commas, but that method will not work for what I'm doing. I believe I need to use the Contains method to let the program know any one of those values will work for that serial number. Any insight or work around?
Thanks
C#

You could split your list of cnumbers by comma and iterate the array checking each cnumber against your value.
if(snumber == "9999-999-9999")
{
var cnumbers = listOfCnumbers.Split(',');
foreach(var cnumber in cnumbers)
{
if(cnumber == "999")
{
return "Good";
}
}
}
Might want to replace the hardcoded strings with variables though

Related

C# Creating a list that takes user input and after prints the number from the list within a certain value range.(please explain how and why it works)

using System;
using System.Collections.Generic;
namespace exercise_69
{
class Program
{
public static void Main(string[] args)
{
List<int> numbers = new List<int>();
//creating a list called numbers
while (true)
{
int input = Convert.ToInt32(Console.ReadLine());
if (input == -1)
{
break;
}
numbers.Add(input);
}
//fills a list called numbers until user enters " -1 "
Console.WriteLine("from where");
int lownum = Convert.ToInt32(Console.ReadLine());
//lowest number to get printed
Console.WriteLine("where to");
int highnum = Convert.ToInt32(Console.ReadLine());
//highest number to get printed
foreach(int number in numbers)
{
if(lownum < number || highnum > number)
{
Console.WriteLine(numbers);
} //trying to filter the numbers and print them
}
}
}
}
Blockquote
the issue i am having is when i run the program the console just tells me this
"System.Collections.Generic.List`1[System.Int32]"
so my question is how do i properly filter or remove numbers from a list within a certain value ( not index )
the console just tells me this "System.Collections.Generic.List`1[System.Int32]"
That's because you did this:
Console.WriteLine(numbers);
numbers is a List<int>, it's a whole collection of numbers not just a single number. Console.WriteLine has many varaitions ("overloads") that know how to do all different kinds of things. It has a large quantity of specific variations for numbers, strings, etc and there is one variation that's like a "catch-all" - it accepts an object which means it can accept pretty much anything in the C# universe. The only thing it does with it, if you do manage to end up using this variation (overload), is call ToString() on whatever you passed in, and then print the string it gets back.
Because you passed a List<int> in, and Console.WriteLine doesn't have any variation that does anything cool with a List specifically, it means your passed-in List gets treated by the catch-all version of WriteLine; "call ToString on what was passed in and print the result". Because List doesn't have a very specific or interesting ToString() of its own, it just inherits a version of ToString() from object, the most simple root of all things in C#. Object's ToString() doesn't do very much - it just returns the type of the object which, in this case, is a "System.Collections.Generic.List`1[System.Int32]".. and that's why you see what you see in the console
Now that you know why your code is printing the type of the List, because you're passing in a List, can you see how to change it so you're passing in something else (like, e.g. an actual number you want to print) ?
Console.WriteLine(numbers);
^^^^^^^
this needs to be something else - can you work out what?

Fastest way to find which is the longest string from a set contained in an input string

I have a very large List<MyClass> (approximatively 600.000 records +) in which i need to extract the record where MyClass.Property1 is the exact match or the closest of my input string. However even if it seems it, this is not a fuzzy string matching problem, so i can't use the Levenshtein distance. To clear the things a bit i'll give you an example.
Suppose that the following is my data set (listing only MyClass.Property1):
242
2421
2422
24220
24221
24222
24223
24224
Now what i expect is, if i have in input 2422 i expect the third record to be given in output. If i get in input 24210 i expect in output the second record, which is the longest string contained in my output. To make the things faster, when i fill the List<MyClass>, i have saved in a Dictionary<int,int> the index at which the first number in the string change (example from 19999 to 20000) so i can reduce the size of the dataset i'm going to search for the match. What i wonder is: Which is the fastest way to reach my goal?
The only thing i can think is something like that:
Since i'm sure that the List<MyClass> is ordered by the MyClass.Property1 like in the example, and supposing that i have extracted a List<MyClass> called SubSet based on the dictionary i mentioned before, i would do
MyClass result = null;
foreach(MyCLass m in SubSet)
{
if (input.Contains(m.Property1))
{
// if the 2 strings are equal i've found the exact match
if(input == m.Property1)
return m.Property1;
else
result = m;
}
else
return result;
}
The most obvious problem i can see here is the fact that if the desidered result is at the end of the SubSet i need to loop over thousands of records Can you think any better way to reach my goal or a way to improve my current code?
Maybe,You can use Linq method in recursive function like
public string test(string input)
{
string result = Subset.FirstOrDefault(a => a == input);
if (result == null)
return test(input.Substring(0, input.Length - 2));
else
return result;
}

Check if Characters in ArrayList C# exist - C# (2.0)

I was wondering if there is a way in an ArrayList that I can search to see if the record contains a certain characters, If so then grab the whole entire sentence and put in into a string. For Example:
list[0] = "C:\Test3\One_Title_Here.pdf";
list[1] = "D:\Two_Here.pdf";
list[2] = "C:\Test\Hmmm_Joke.pdf";
list[3] = "C:\Test2\Testing.pdf";
Looking for: "Hmmm_Joke.pdf"
Want to get: "C:\Test\Hmmm_Joke.pdf" and put it in the Remove()
protected void RemoveOther(ArrayList list, string Field)
{
string removeStr;
-- Put code in here to search for part of a string which is Field --
-- Grab that string here and put it into a new variable --
list.Contains();
list.Remove(removeStr);
}
Hope this makes sense. Thanks.
Loop through each string in the array list and if the string does not contain the search term then add it to new list, like this:
string searchString = "Hmmm_Joke.pdf";
ArrayList newList = new ArrayList();
foreach(string item in list)
{
if(!item.ToLower().Contains(searchString.ToLower()))
{
newList.Add(item);
}
}
Now you can work with the new list that has excluded any matches of the search string value.
Note: Made string be lowercase for comparison to avoid casing issues.
In order to remove a value from your ArrayList you'll need to loop through the values and check each one to see if it contains the desired value. Keep track of that index, or indexes if there are many.
Then after you have found all of the values you wish to remove, you can call ArrayList.RemoveAt to remove the values you want. If you are removing multiple values, start with the largest index and then process the smaller indexes, otherwise, the indexes will be off if you remove the smallest first.
This will do the job without raising an InvalidOperationException:
string searchString = "Hmmm_Joke.pdf";
foreach (string item in list.ToArray())
{
if (item.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
{
list.Remove(item);
}
}
I also made it case insensitive.
Good luck with your task.
I would rather use LINQ to solve this. Since IEnumerables are immutable, we should first get what we want removed and then, remove it.
var toDelete = Array.FindAll(list.ToArray(), s =>
s.ToString().IndexOf("Hmmm_Joke.pdf", StringComparison.OrdinalIgnoreCase) >= 0
).ToList();
toDelete.ForEach(item => list.Remove(item));
Of course, use a variable where is hardcoded.
I would also recommend read this question: Case insensitive 'Contains(string)'
It discuss the proper way to work with characters, since convert to Upper case/Lower case since it costs a lot of performance and may result in unexpected behaviours when dealing with file names like: 文書.pdf

C# if string contains more than 1 value

Good Morning,
In an if statement if we want to check if a string contains a value, we have :
if (string.Contains("Value1"))
{
}
How can we make the string compare with more values in an if statement without keep writing the whole statement? For example to avoid the below statement
if ((string.Contains("Value1") && (string.Contains("Value2")) && (string.Contains("Value3")))
{
}
Thank you
So, basically, you want to check if all of your values are contained in the string . Fortunately (with the help of LINQ), this can by translated almost literally into C#:
var values = new String[] {"Value1", "Value2", "Value3"};
if (values.All(v => myString.Contains(v))) {
...
}
Similarly, if you want to check if any value is contained in the string, you'd substitute All by Any.
Well, you could use LINQ:
string[] requiredContents = { "Foo", "Bar", "Baz" };
if (requiredContents.All(x => text.Contains(x))
{
...
}
Note that just like the short-circuiting && operator, All will stop as soon as it finds a value which doesn't satisfy the condition. (If you want to use Any in a similar way elsewhere, that will stop as soon as it finds a value which does satisfy the condition.)
I wouldn't bother for only a reasonably small number though. Without the extraneous brackets, it's really not that bad:
if (text.Contains("foo") && text.Contains("bar") && text.Contains("Baz"))
{
}
I would only start using the more general form if either there were genuinely quite a few values (I'd probably draw the line at about 5) or if the set of values was being passed in as a parameter, or varied in some other way.
As you need "your" string to contains all values:
var values = new String[] {"Value1", "Value2", "Value3"};
var s = yourString;
if (values.Count(v => s.Contains(v)) == values.Length) {
...
}
Is this the best solution? Probably not. Is it readable and extendable? Yes.
var matches = {"string1", "string2", "string3","string-n"};
var i = 0;
foreach(string s in matches)
{
if(mystring.Contains(s))
{
i++;
}
}
if(i == matches.Length)
{
//string contains all matches.
}
if(stringArray.Any(s => stringToCheck.Contains(s)))
If you want to ensure that it contains all the substrings, change Any to All:
if(stringArray.All(s => stringToCheck.Contains(s)))

C# Array contains partial

How to find whether a string array contains some part of string?
I have array like this
String[] stringArray = new [] { "abc#gmail.com", "cde#yahoo.com", "#gmail.com" };
string str = "coure06#gmail.com"
if (stringArray.Any(x => x.Contains(str)))
{
//this if condition is never true
}
i want to run this if block when str contains a string thats completely or part of any of array's Item.
Assuming you've got LINQ available:
bool partialMatch = stringArray.Any(x => str.Contains(x));
Even without LINQ it's easy:
bool partialMatch = Array.Exists(stringArray, x => str.Contains(x));
or using C# 2:
bool partialMatch = Array.Exists(stringArray,
delegate(string x) { return str.Contains(x)); });
If you're using C# 1 then you probably have to do it the hard way :)
If you're looking for if a particular string in your array contains just "#gmail.com" instead of "abc#gmail.com" you have a couple of options.
On the input side, there are a variety of questions here on SO which will point you in the direction you need to go to validate that your input is a valid email address.
If you can only check on the back end, I'd do something like:
emailStr = "#gmail.com";
if(str.Contains(emailStr) && str.length == emailStr.length)
{
//your processing here
}
You can also use Regex matching, but I'm not nearly familiar enough with that to tell you what pattern you'd need.
If you're looking for just anything containing "#gmail.com", Jon's answer is your best bets.

Categories

Resources