我可以使用 Linq 來做到這一點,但我很難做到這一點,如果可能的話,我寧愿不要:
使用 LINQ 的代碼:
string result = sentencewithint
.Split("")
.FirstOrDefault(item => Regex.IsMatch(item, @"^\-?[0-9] $"));
int firstint = int.Parse(result);
return firstint;
uj5u.com熱心網友回復:
你可以使用 regex
string sentencewithint = "1567438absdg345";
string result = Regex.Match(sentencewithint, @"^\d ").ToString();
Console.WriteLine(result); //1567438
或者使用TakeWhile擴展方法從條件中的字串中獲取字符,僅當它們是數字時
string sentencewithint = "1567438absdg345";
string num = new String(sentencewithint.TakeWhile(Char.IsDigit).ToArray());
Console.WriteLine(result); //1567438
uj5u.com熱心網友回復:
您可以放置??一個簡單的回圈而不是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;
uj5u.com熱心網友回復:
.Split不是 Linq 方法。您使用的唯一 Linq 是FirstOrDefault. 但是要回答您的問題,所有 .Net 都是開源的,因此您可以查找源代碼并復制它。
這里是 的源代碼FirstOrDefault。你可以這樣寫自己的FirstOrDefaultMethod:
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;
}
這是 的源代碼string,其中包括Split第 975 行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/350050.html
