I'm developing a WPF with C# and .NET Framework 4.6.1.
I was using this line of code:
codesRead.IndexOf(string.Format("{0} OK", lastCode));
codesRead is a private readonly ObservableCollection<string>.
It was working very fine when I was using these strings "code1 OK".
Now I have changed the strings with these ones "code1 OK - 23.0005 ms" and now it always returns -1.
How can I find the index of a string that begins with "code1 OK"?
you can use the Find clause to get the element and then search for it with IndexOf. Here is a small console application to illustrate this:
List<string> asd = new List<string>
{ "code5 OK - 234", "code2 OK - 234", "code1 OK - 234", "code4 FAIL - 234" };
int index = asd.IndexOf(asd.Find(x => x.StartsWith("code1")));
Console.WriteLine(index);
It will return -1 if the element does not exist
EDIT: Sorry, I did not read accurately enough your post apparently.
If you are using an ObservableCollection I would suggest to use FirstOrDefault to search for the item. Here is an example with a negative outcome:
ObservableCollection<string> qwe = new ObservableCollection<string>()
{ "code5 OK - 234", "code2 OK - 234", "code7 OK - 234" };
int index = qwe.IndexOf(qwe.FirstOrDefault(x => x.StartsWith("code1")));
Console.WriteLine(index);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With