Telegram Group & Telegram Channel
🖥 Прочитать Nullable<long> из строки

Итак, дан код:

long? catCode = null;
// Если строка val не пустая,
if (!(String.IsNullOrWhiteSpace(val)))
{
// распознаем в первых цифрах до пробела целое 64-битное число.
// Если его там нет, записываем в catCode NULL.
// Если его удалось распознать, записываем его в catCode.
if (!(Int64.TryParse(val.Split(" ")[0], out long cc)))
{
catCode = null;
}
else
{
catCode = cc;
}
}

Как переписать этот код чуть понятнее?

Как вариант, можно написать что-то в духе:

public static string LeftDigits(this string str)
{
if (str == null) return null;
if (!str.contains(" ") return null;
string left = str.Split(" ")[0];
if (! left.All(Char.IsDigit){
return null;
}
return left;
}

//...

string digits = LeftDigits(val);
long? catCode = digits != null ? Int64.Parse(digits) : null;

А есть ли ещё варианты?
Можете накидать свои в комментах

@csharp_1001_notes
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/csharp_1001_notes/433
Create:
Last Update:

🖥 Прочитать Nullable<long> из строки

Итак, дан код:


long? catCode = null;
// Если строка val не пустая,
if (!(String.IsNullOrWhiteSpace(val)))
{
// распознаем в первых цифрах до пробела целое 64-битное число.
// Если его там нет, записываем в catCode NULL.
// Если его удалось распознать, записываем его в catCode.
if (!(Int64.TryParse(val.Split(" ")[0], out long cc)))
{
catCode = null;
}
else
{
catCode = cc;
}
}

Как переписать этот код чуть понятнее?

Как вариант, можно написать что-то в духе:

public static string LeftDigits(this string str)
{
if (str == null) return null;
if (!str.contains(" ") return null;
string left = str.Split(" ")[0];
if (! left.All(Char.IsDigit){
return null;
}
return left;
}

//...

string digits = LeftDigits(val);
long? catCode = digits != null ? Int64.Parse(digits) : null;

А есть ли ещё варианты?
Можете накидать свои в комментах

@csharp_1001_notes

BY C# 1001 notes




Share with your friend now:
tg-me.com/csharp_1001_notes/433

View MORE
Open in Telegram


C 1001 notes Telegram | DID YOU KNOW?

Date: |

How to Use Bitcoin?

n the U.S. people generally use Bitcoin as an alternative investment, helping diversify a portfolio apart from stocks and bonds. You can also use Bitcoin to make purchases, but the number of vendors that accept the cryptocurrency is still limited. Big companies that accept Bitcoin include Overstock, AT&T and Twitch. You may also find that some small local retailers or certain websites take Bitcoin, but you’ll have to do some digging. That said, PayPal has announced that it will enable cryptocurrency as a funding source for purchases this year, financing purchases by automatically converting crypto holdings to fiat currency for users. “They have 346 million users and they’re connected to 26 million merchants,” says Spencer Montgomery, founder of Uinta Crypto Consulting. “It’s huge.”

C 1001 notes from tw


Telegram C# 1001 notes
FROM USA