Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# get also the key from parsing substring from string

I would like to refactor my method. I also need to get which value was first? So which anyOf? Is it possible to get it from here?

Example:

List<string> anyOf = new List<string>(){"at", "near", "by", "above"};
string source = "South Branch Raritan River near High Bridge at NJ"

public static int IndexOfAny(this string source, IEnumerable<string> anyOf, StringComparison stringComparisonType = StringComparison.CurrentCultureIgnoreCase)
{
    var founds = anyOf
        .Select(sub => source.IndexOf(sub, stringComparisonType))
        .Where(i => i >= 0);
    return founds.Any() ? founds.Min() : -1;
}

I would like to get back what is first in string. "near" or "at".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use:

public static (int index, string? firstMatch) IndexOfAny(this string source, IEnumerable<string> anyOf, StringComparison stringComparisonType = StringComparison.CurrentCultureIgnoreCase)
{
    return anyOf
        .Select(s => (Index: source.IndexOf(s, stringComparisonType), String: s))
        .Where(x => x.Index >= 0)
        .DefaultIfEmpty((-1, null))
        .First();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading