Reputation: 2720
Below is the code:
PropertyInfo[] requestPropertyInfo;
requestPropertyInfo = typeof(CBNotesInqAndMaintRequest).GetProperties();
The CBNotesInqAndMaintRequest contains request data member noteline1---noteline18. once I read the name of one of the data member, I want to get its last index. For eg. If the name of the request object is "noteline8", I want to get the index as 8.
For this I have written the below code:
foreach (PropertyInfo reqPropertyInfo in requestPropertyInfo)
{
index = reqPropertyInfo.Name.LastIndexOf("noteline");
}
But the above code is returning the index as 0.
Upvotes: 3
Views: 17510
Reputation: 21
The simplest answer in my opinion is to get the count of the string and then subtract it by 1, will give you the last index of that string as shown below:-
int lastIndex= sampleString.Count-1; //sampleString is the string here.
Upvotes: 0
Reputation: 12682
Edit
Considering your comment, you should do:
Int32 index = Convert.ToInt32(reqPropertyInfo.Name.Replace("noteline",""));
Upvotes: 0
Reputation: 2463
I created a RegEx solution that doesn't matter what the property name is, but grabs the last digits and returns an integer
static int GetLastInteger( string name ) {
int value;
if( int.TryParse( name, out value ) ) {
return value;
}
System.Text.RegularExpressions.Regex r =
new System.Text.RegularExpressions.Regex( @"[^0-9](\d+\b)" );
System.Text.RegularExpressions.Match m =
r.Match( name );
string strValue = m.Groups[1].Value;
value = ( int.Parse( strValue ) );
return value;
}
Usable in your example like so:
foreach (PropertyInfo reqPropertyInfo in requestPropertyInfo)
{
index = GetLastInteger(reqPropertyInfo.Name);
}
Upvotes: 1
Reputation: 136
index = reqPropertyInfo.Name.Length -1;
incase of "noteline18", you want to find the index of 1 instead of 8, then
index = reqPropertyInfo.Name.LastIndexOf('e') + 1
Upvotes: 3
Reputation: 26792
It looks like you want to get the number after 'noteline'. If that is the case:
index = int.Parse(reqPropertyInfo.Name.SubString(8));
Upvotes: 2
Reputation: 1160
It that what you want ?
foreach (PropertyInfo reqPropertyInfo in requestPropertyInfo)
{
index = int.Parse(reqPropertyInfo.Name.Replace("noteline",""));
}
Upvotes: 3
Reputation: 38820
The reason you are getting 0
back is that it is returning the last index of the entire string "noteline", which is of course, always at position 0. If you had "notelinenoteline", it would be returning "8".
Now, as to what you want to get back:
index = reqPropertyInfo.Name.Substring(8);
Upvotes: 1
Reputation: 7708
LastIndexOf
returns the starting index of the string that you're looking for, which is why it returns 0.
Upvotes: 0