Home > Mobile >  Using .Split to Split a string and return first integer values (Without LINQ)
Using .Split to Split a string and return first integer values (Without LINQ)

Time:11-05

I am able to use Linq to do this but I am struggling to do it without, would prefer without if possible:

Code with LINQ:

        string result = sentencewithint
                .Split("")
                .FirstOrDefault(item => Regex.IsMatch(item, @"^\-?[0-9] $"));

        int firstint = int.Parse(result);

        return firstint;

CodePudding user response:

You can do it using regex

string sentencewithint = "1567438absdg345";
string result = Regex.Match(sentencewithint, @"^\d ").ToString();
Console.WriteLine(result); //1567438

Or using the TakeWhile extension methods to get characters from the string in the condition only if they are digits

string sentencewithint = "1567438absdg345";
string num = new String(sentencewithint.TakeWhile(Char.IsDigit).ToArray());  
Console.WriteLine(result); //1567438

CodePudding user response:

You can put a simple loop instead of Linq:

foreach (string item in sentencewithint.Split(""))
  if (Regex.IsMatch(item, @"^\-?[0-9] $"))
    return int.Parse(item);

//TODO: Put some default value here (in case no item has been matched)
return -1;

CodePudding user response:

.Split is not a Linq method. The only Linq you are using is FirstOrDefault. But to answer your question, all of .Net is open source, so you can look up the source code and copy that.

Here is the source code for FirstOrDefault. You could write your own FirstOrDefaultMethod like this:

    public static TSource? FirstOrDefault<TSource>(this IEnumerable<TSource> source) =>
        source.TryGetFirst(out _);
    private static TSource? TryGetFirst<TSource>(this IEnumerable<TSource> source, out bool found)
    {
        if (source == null)
        {
            ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
        }

        if (source is IPartition<TSource> partition)
        {
            return partition.TryGetFirst(out found);
        }

        if (source is IList<TSource> list)
        {
            if (list.Count > 0)
            {
                found = true;
                return list[0];
            }
        }
        else
        {
            using (IEnumerator<TSource> e = source.GetEnumerator())
            {
                if (e.MoveNext())
                {
                    found = true;
                    return e.Current;
                }
            }
        }

        found = false;
        return default;
    }

Here is the source code for string, which includes Split on line 975.

  • Related