What is wrong with this code? why the List does not identify? - asp.net

what is wrong with this code?
bool claimExists;
string currentClaimControlNo = "700209308399870";
List<string> claimControlNo = new List<string>();
claimControlNo.Add("700209308399870");
if (claimControlNo.Contains(currentClaimControlNo.Substring(0, 14)))
claimExists = true;
else
claimExists = false;
Why the claimControlNo above is coming into false?
Since I know the value exists, how can i tune the code?

It's reporting false because you aren't asking whether the list contains the currentClaimControlNo, you're asking whether it contains a string that is the first fourteen characters of the fifteen-character string currentClaimControlNo.
Try this instead:
claimExists = claimControlNo.Any(ccn => ccn.StartsWith(currentClaimControlNo.Substring(0,14)));

Your count is wrong. There are 15 characters. Your substring is cutting off the last 0 which fails the condition.

Because you're shaving off the last digit in your substring.
if you change the line
if (claimControlNo.Contains(currentClaimControlNo.Substring(0, 14)))
to
if (claimControlNo.Contains(currentClaimControlNo.Substring(0, 15)))
it works.

Because contains on a list looks for the whole item, not a substring:
currentClaimControlNo.Substring(0, 14)
"70020930839987"
Is not the same as
700209308399870
You're missing a digit, hence why your list search is failing.
I think you are trying to find something in the list that contains that substring. Don't use the lists contain method. If you are trying to find something in the list that has the subset do this
claimExists = claimControlNo.Any(item => item.Contains(currentClaimControlNo.Substring(0, 14)))
This goes through each item in claimControlNo and each item can then check if it contains the substring.
Why do it this way? The Contains method on a string
Returns a value indicating whether the specified System.String object occurs within this string.
Which is what you want.
Contains on a list, however
Determines whether an element is in the System.Collections.Generic.List.
They aren't the same, hence your confusion

Do you really need this explaining?
You are calling Substring for 14 characters when the string is of length 15. Then you are checking if your list (which only has one item of length 15) contains an item of length 14. It doesn;t event need to check the value, the length is enough to determine it is not a match.
The solution of course is to not do the Substring, it makes not sense.
Which would look like this:
if (claimControlNo.Contains(currentClaimControlNo))
claimExists = true;
else
claimExists = false;
Then again, perhaps you know you are trimming the search, and are in fact looking for anything that has a partial match within the list?
If this is the case, then you can simply loop the list and do a Contains on each item. Something like this:
bool claimExists = false;
string searchString = currentClaimControlNo.Substring(0, 14);
foreach(var s in claimControlNo)
{
if(s.Contains(searchString))
{
claimExists = true;
break;
}
}
Or use some slightly complex (certainly more complex then I can remember off the top of my head) LINQ query. Quick guess (it's probably right to be fair, I am pretty freaking awesome):
bool claimExists = claimControlNo.Any(x => x.Contains(searchString));

Check it:
// str will be equal to 70020930839987
var str = currentClaimControlNo.Substring(0, 14);
List<string> claimControlNo = new List<string>();
claimControlNo.Add("700209308399870");
The value str isn't contained in the list.

Related

Populating an Apex Map from a SOQL query

// I have a custom metadata object named boatNames__mdt and I'm using two methods to get a list of picklist values in a String[];
First Method
Map<String, boatNames__mdt> mapEd = boatNames__mdt.getAll();
string boatTypes = (string) mapEd.values()[0].BoatPick__c;
// BoatPick__c is a textarea field (Eg: 'Yacht, Sailboat')
string[] btWRAP = new string[]{};
**btWRAP**.addAll(boatTypes.normalizeSpace().split(','));
Second Method
string[] strL = new string[]{};
Schema.DescribeFieldResult dfr = Schema.SObjectType.boatNames__mdt.fields.BoatTypesPicklist__c;
// BoatTypesPicklist__c is a picklist field (Picklist Values: 'Yacht, Sailboat')
PicklistEntry[] picklistValues = dfr.getPicklistValues();
for (PicklistEntry pick : picklistValues){
**strl**.add((string) pick.getLabel());
}
Map with SOQL query
Map<Id, BoatType__c> boatMap = new Map<Id, BoatType__c>
([Select Id, Name from BoatType__c Where Name in :btWRAP]);
When I run the above Map with SOQL query(btWRAP[]) no records show up.
But when I used it using the strl[] records do show up.
I'm stunned!
Can you please explain why two identical String[] when used in exact SOQL queries behave so different?
You are comparing different things so you get different results. Multiple fails here.
mapEd.values()[0].BoatPick__c - this takes 1st element. At random. Are you sure you have only 1 element in there? You might be getting random results, good luck debugging.
normalizeSpace() and trim() - you trim the string but after splitting you don't trim the components. You don't have Sailboat, you have {space}Sailboat
String s = 'Yacht, Sailboat';
List<String> tokens = s.normalizeSpace().split(',');
System.debug(tokens.size()); // "2"
System.debug(tokens); // "(Yacht, Sailboat)", note the extra space
System.debug(tokens[1].charAt(0)); // "32", space's ASCII number
Try splitting by "comma, optionally followed by space/tab/newline/any other whitespace symbol": s.split(',\\s*'); or call normalize in a loop over the split's results?
pick.getLabel() - in code never compare using picklist labels unless you really know what you're doing. Somebody will translate the org to German, French etc and your code will break. Compare to getValue()

Get word at position in Atom

From a linter provider, I receive a Point compatible array(line, column) where the error occured. Now I would like to hightlight the word surrounding that point, basically the result one would get if that exact point was double-clicked in the editor. Something like
const range = textEditor.getWordAtPosition(point)
Is what I hoped for, but couldn't find in the documentation.
Thanks for your help!
After looking around for a while, there seems to be no API method for the given need. I ended up writing a small helper function based upon this answer:
function getWordAtPosition(line, pos) {
// Perform type conversions.
line = String(line);
pos = Number(pos) >>> 0;
// Search for the word's beginning and end.
const left = Math.max.apply(null, [/\((?=[^(]*$)/,/\)(?=[^)]*$)/, /\,(?=[^,]*$)/, /\[(?=[^[]*$)/, /\](?=[^]]*$)/, /\;(?=[^;]*$)/, /\.(?=[^.]*$)/, /\s(?=[^\s]*$)/].map(x => line.slice(0, pos).search(x))) + 1
let right = line.slice(pos).search(/\s|\(|\)|\,|\.|\[|\]|\;/)
// The last word in the string is a special case.
if (right < 0) {
right = line.length - 1
}
// Return the word, using the located bounds to extract it from the string.
return str.slice(left, right + pos)
}
Here, the beginning of the word is determined by the latest occurance of one of the characters (),.[]; or a blank.
The end of the word is determined by the same characters, however here the first occurance is taken as a delimeter.
Given the original context, the function can the be called using the API method ::lineTextForBufferRow and the desired postion (column) as follows:
const range = getWordAtPosition(textEditor.lineTextForBufferRow(bufferRow), 10)

textbox is empty but still showing the count

I have textbox1 field in asp.net and a text area to show count of records.
I want to count the records split by , in textbox1 but when textbox1 is empty text area is showing 1.
Here is the code.
int contacts = textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
String.Split always returns at least one string, if you pass string.Empty you will get one string which is the input string(so in this case string.Empty).
Documentation:
....
If this instance does not contain any of the characters in separator,
the returned array consists of a single element that contains this instance.
You have to check it, f.e. with string.IsNullOrEmpty(or String.IsNullOrWhiteSpace):
int contacts = 0;
if(!string.IsNullOrEmpty(textbox1.Text))
contacts = textbox1.Text.Split(',').Length;
Try this
int contacts = string.IsNullOrEmpty(string.textbox1.Text)? string.empty: textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
This is because even when textbox1.Text is an empty string, that's still treated as one item. You need to use StringSplitOptions.RemoveEmptyEntries so that empty entries are ignored when producing the result of calling Split:
var contacts = textbox1.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Count();
To decompose what you've written into individual statements, what you have is:
var items = textbox1.Text.Split(new char[] { ', ' }, StringSplitOptions.RemoveEmptyEntries);
var countOfItems = itemsFromText.Count();
If you look at items you'll see that it's an array of strings (string[]) which contains one entry for each item in the text from textbox1.Text.
Even if an empty string is passed in (i.e. textbox1 is empty) there's still one string to be returned, hence the fact that your code as written is returning 1, whereas in countOfItems where I've broken the code apart it will have 0 because of the use of StringSplitOptions.RemoveEmptyEntries.
The documentation on msdn of the String.Split overload that takes StringSplitOptions as a parameter has more examples and detail about this.

Cannot Solve "index was outside the bounds of the array"

I am working in C# with ASP.NET. I am familiar with this error but this time I can't solve it.
I have text in a drop-down list like this:
राम कुमार सिंह 8s2w8r
here राम कुमार सिंह is the name in HINDI while 8s2w8r is users' ID.
I need to separate these two values and need to pass them as session variables. The logic I am using is depicted in the code.
public string reverse(string s)
{
char []temp=s.ToCharArray();
Array.Reverse(temp);
return (temp.ToString());
}
string dropdowntextreversed=reverse(DropDownList1.Text);
char []delim=new char[]{' '};
string []parts=dropdowntextreversed.Split(delim,2);
string family_head_uid = reverse(parts[0]);
string family_head = reverse(parts[1]);
Session.Add("family_head", family_head);
Session.Add("family_head_uid", family_head_uid);
Response.Redirect("/WebForm1.aspx");
I always get an error as the index was outside the bounds of the array! I don't understand this because I am breaking the string into 2 parts so it should have parts[0] and parts[1]. Please suggest...
You are splitting the string into MAXIMUM 2 parts, but if there's only one you will get probably one part.
Read this documentation
Try to assert that parts.Length is == 2 or to access elemnts only there atre two elements
Try this link. As I think there is a problem in the temp.ToString() which will return System.Char[] rather than the value which are you looking for. Use string.join instead will work.
Use the following reverse method:
public string reverse(string s)
{
return String.Join(String.Empty, s.ToCharArray().Reverse());
}

Replace string from character onwards

I've got a string like so
Jamie(123)
And I'm trying to just show Jamie without the brackets etc
All the names are different lengths so I was wondering if there was a simple way of replacing everything from the first bracket onwards?
Some others are displayed like this
Tom(Test(123))
Jack ((4u72))
I've got a simple replace of the bracket at the moment like this
mystring.Replace("(", "").Replace(")","")
Any help would be appreciated
Thanks
VB.NET
mystring.Substring(0, mystring.IndexOf("("C)).Trim()
C#
mystring.Substring(0, mystring.IndexOf('(')).Trim();
One logic; get the index of the ( and you can trim the later part from that position.
public static string Remove(string value)
{
int pos = value.IndexOf("(");
if (pos >= 0)
{
return value.Remove(pos, remove.Length);
}
return value;
}
aneal's will work. The alternative I generally use because it's a bit more flexible is .substring.
string newstring = oldstring.substring(0,oldstring.indexof("("));
If you aren't sure that oldstring will have a "(" you will have to do the test first just as aneal shows in their answer.
String.Remove(Int32) will do what you need:
Deletes all the characters from this string beginning at a
specified position and continuing through the last position.
You will also have to .Trim() as well given the data with padding:
mystring = mystring.Remove(mystring.IndexOf("("C))).Trim()

Resources