Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index of a string that begins with

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"?

like image 941
VansFannel Avatar asked Dec 01 '25 06:12

VansFannel


1 Answers

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);
like image 107
Mong Zhu Avatar answered Dec 03 '25 20:12

Mong Zhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!