Array failed to know if it contains a string - c#

I must doing something wrong... But I can't figure it out!
I have an array with string in it. I'm trying to fins if the Array contains some words like Sales for example.
drillDownUniqueNameArray[0] = "[Sales Territory].[Sales Territories].[Sales Territory Group].&[North America]";//Inside the string array there is this string in index 0
drillDownUniqueNameArray.Contains("S")//Output false!
Array.IndexOf(drillDownUniqueNameArray,"S")//Output -1! <--Fixed My answer
drillDownUniqueNameArray.Contains("[Sales Territory].[Sales Territories].[Sales Territory Group].&[North America]") //Output true!
I thouhgt Contains should find even part of the string..
How can I find if this array have "S" or "Sales" for example?

You are asking if the array contains a string that exactly matches "S".
What you want is to ask if any of the strings in the array contains the character "S", something like:
drillDownUniqueNameArray.Any(v => v.Contains("S"))

You're checking if the array contains an element that's exactly "S" but I think you are trying to check whether the array contains an alement that contains an "S".
You could achieve this by the following statement:
drillDownUniqueNameArray.Any( str => str.Contains ("S") )

You can try this.
drillDownUniqueNameArray[0].Contains("s");

You can use LINQ:
var allWithSales = drillDownUniqueNameArray
.Where(str => str.Contains("Sales"));
ignoring the case:
var allWithSalesIgnoreCase = drillDownUniqueNameArray
.Where(str => str.IndexOf("sales", StringComparison.OrdinalIgnoreCase) >= 0);
If you want to find all that contain a word "Sales"(String.Split() = white-space delimiter)):
var allWordsWithSales = drillDownUniqueNameArray
.Where(str => str.Split().Contains("Sales", StringComparer.OrdinalIgnoreCase));
Now you can enumerate the query with foreach or use ToArray() or ToList to create a collection:
foreach(string str in allWithSales)
Console.WriteLine(str);

You are finding it in the array, but you should find the word in the string.
Use following if you want to check:
drillDownUniqueNameArray.Any(x=>x.Contains("Sales"));
Use following if want to get the strings which contains "Sales"
drillDownUniqueNameArray.Where(x=>x.Contains("Sales"));

When you do it like this:
drillDownUniqueNameArray.Contains("S")
it's not gonna check the values, you must do it like this:
drillDownUniqueNameArray[0].Contains("S") or drillDownUniqueNameArray.First().Contains("S")
like this way it checks the values inside the array not the arrays itself

Related

How to remove character from string?

I have a string which is getting from a userInput. What I want to do now is removing a unique character from this string but only remove it once. The main problem is that this unique character doesn't have a unique index. For example:
User has input a string like : "0123456", and now I want to remove the first '1',so the string will be output like "023456". How ever, if a user input a string like "01123456", how can I remove the first '1' and make it looks like "0123456"? I am looking for a method that can be used for both of situation. I was using string.TrimStart(), but doesn't get what I want. How can I do this?
You could use Remove and IndexOf.
var str = "01123456";
var i = str.IndexOf('1'); // IndexOf returns -1 when there is no element found, so we need to handle that when calling remove.
var res = (i >= 0) ? str.Remove(i, 1) : str;
Console.WriteLine(res); // 0123456
I think you what you need is string.Remove method. See MSDN documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.string.remove?view=netframework-4.7.2#System_String_Remove_System_Int32_System_Int32_
If you don't know where is your character, at first call string.IndexOf to find it. If this call returns nonnegaive number, call Remove to remove it. Just note that string is immutable so it will always create a new object.
yourstring = yourstring.IndexOf('1') != -1 ? yourstring.Remove(yourstring.IndexOf('1'), 1) : yourstring;
Another way would be to use a combination of Contains, Remove, and IndexOf:
if (userInput.Contains('1')) userInput = userInput.Remove(userInput.IndexOf('1'), 1);
Or if you want to be Linq-y...
userInput = string.Concat(userInput.TakeWhile(chr => chr != '1')
.Concat(userInput.SkipWhile(chr => chr != '1').Skip(1)));

Is there a way to get the length of a return value in the same line of code?

I'm not sure if I worded that right but heres what I'm looking for.
I would like to do something like this:
string lastWord = words.Split(':')[splitResult.Length -1];
Is there any way to make that happen or must I store the array first?
using Linq, LastOrDefault extention.
string lastword = words.Split(':').LastOrDefault();
If I would use Split, wouldnt I be splitting it twice?
It Depends.
if you do below, yes you are splitting twice.
string lastWord = words.Split(':')[words.Split(':').Length -1];
and if you use temporary variable for splits then you need Split only once.
var splits =words.Split(':');
string lastWord = splits[splits.Length -1];

C# How to check if a string contains a specifc combination of chars

I have a List, named values which contains values similar to the following string values:
GKgpuzjBUh
IS1bbf2ffd806f6d
IS102a8a395ced93
Dark Von Diakonov
IS148159f7c24f78
I need to check if the specific a string in the starts with IS1
You dont need regex. Use str.StartsWith("IS1").
Not clear from the question, so here are a few options.
You want to find out if ANY string in the list starts with IS1
var found = values.Any(item => item.StartsWith("IS1"));
You want to find all the strings in the list which start with IS1
var matches = values.Where(item => item.StartsWith("IS1"));

Filter array of string and get only matching ones with searched string

I have an array of string and I want to get back from it a filtered array that contains only those strings that match the searched string.
string[] myValues = {"School.Report1", "School.Report2", "School.Report3", "House.Report1", "House.Report2"};
string myFilter = "School";
string[] filteredValues = myValues.Filter(myFilter); // or something similar
filteredValues must contains only: "School.Report1", "School.Report2", "School.Report3".
-- EDIT --
I prefer a non-LINQ approach if possibile. Otherwise I know that this question can be answered with the solution proposed here: filter an array in C#.
If you can't use LINQ you can still use Array.FindAll:
string[] filteredValues = Array.FindAll(myValues, s => s.Contains(myFilter));
or maybe you want to keep only all strings which first token(separated by dot) is School:
string[] filteredValues = Array.FindAll(myValues, s => s.Split('.')[0] == myFilter);
One possible answer is to make an IComparer that sorts the array by the matching value (if it contains filter return 1 else return 0) then find the first item outside the filter and make another array with the values up the one before that point.

Parsing similar named parameters out of a URL

I'm taking a URL that looks like this:
some_site.com/full/path/page.aspx?label[0]=a_value&label[1]=b_value&label[2]=c_value
The indexed number is generated, so there's a dynamic number of these 'label[x]' values every time.
What would the simplest way of parsing these all into a String[] named 'Label' in ASP/C#.NET 4.0?
You should use a NameValueCollection instead of array of Strings.
NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
string[] parts = segment.Split('=');
if (parts.Length > 0)
{
string key = parts[0].Trim(new char[] { '?', ' ' });
string val = parts[1].Trim();
queryParameters.Add(key, val);
}
}
To get the number of the label withing the square brackets, use Regular Expressions.
regxObj = new Regex(#"\[(.*?)\]");
Have you thought about enumerating the entries in the Request.Querystring collection?
You can start by taking the substring from the index of '?' to the end, then split by '&'.
Then you can either loop through that list and split by '=' and take the second element, or the substring of each of those starting after the index of '='.
If you do want it as just and array of strings for some reason, this one line will probably work.
String[] labels = (from substring in s.Substring(s.IndexOf('?') + 1).Split('&') select substring.Substring(substring.IndexOf('=') + 1)).ToArray();
edit: Do note that this disregards what the actual labels are, as well as their numbers; if there's something other than named, numbered label[n] tags, those will be added as to the array as well.
make a parameter called length
some_site.com/full/path/page.aspx?length=4&label[0]=a_value&label[1]=b_value&label[2]=c_value...
then that will be easy to parse on the other side already knowing the length
if you know the length , then you know how many times to iterate through a loop to read the values of querystring
-or-
don't have a variable amount of parametes , use one , and use any special character to seperate them, then split the value by the seperating char on the other side

Categories