Use Regex in this Linq query?
I am using this Linq to find the highest int in a list, so that I can increment it and add to the end of the next line:
var CableNumber = CList.Select(v => int.Parse(v.CableNumber.Substring(n))).Max();
However, since strings are not fixed length, I was thinking about inserting Regex.Match
there, perhaps something like:
n = Regex.Match(CableNumber, @"\d{3}", RegexOptions.RightToLeft);
To indicate; the only format the input strings follow is that it will always have a 3-digit number at the end, possibly followed by one letter. Some examples:
CP1-P-CP2-001 (001)
MOT1PSP2023A (023)
TKSP3-C-FLT2-234-A (234)
How could I have implemented this? Is there a better way?
source to share
The following uses the regex pattern inside a linq query:
string[] strings = { "CP1-P-CP2-001 (001)","MOT1PSP2023A (023)", "TKSP3-C-FLT2-234-A (234)",
"InvalidString" };
int? maxValue = strings.Max(x =>
{
var match = Regex.Match(x, @"\d{3}(?=\D*$)");
return match.Success ? (int?) int.Parse(match.Value) : null;
});
int?
is that we can get around any string.Empty
, returning from an incorrect match, and only parses. If none of them match, null is returned.
source to share
How about this?
var CableNumber = CList.Select(v =>
int.Parse(v.CableNumber.Substring(v.CableNumber.Length - 3))).Max();
Or be safe (to prevent a string that is less than 3 characters).
var CableNumber = CList.Select(v =>
int.Parse(("000" + v.CableNumber).Substring(("000" + v.CableNumber).Length - 3))).Max();
Update
Use LastIndexOfAny
var CableNumber = CList.Select(v =>
int.Parse(v.CableNumber.Substring(v.CableNumber
.LastIndexOfAny("0123456789".ToCharArray()) - 2, 3))).Max();
source to share