Reputation:
How to check for integer in one line?
sample.AddRange(Statistics.Select(player => new Stats
{
SeasonFromYear = Convert.ToInt32(seasonFromYear)
}
This one is working for me.
int a;
SeasonFromYear = int.TryParse(seasonFromYear, out a) ? a : default(int);
But for every property i need to declare one variable like a
. Without that is it possible to check in one line?
Something like this
sample.AddRange(Statistics.Select(player => new Stats
{
SeasonFromYear = is integer ? then value : else default value
}
Upvotes: 10
Views: 4809
Reputation: 119
I know this is old but for one line just declare a in the TryParse:
SeasonFromYear = int.TryParse(seasonFromYear, out int a) ? a : default(int);
Put whatever default value you want where default(int) is.
Upvotes: 1
Reputation: 5899
You can create extension method:
public static int ToInt(this string v)
{
int a = 0;
int.TryParse(v, out a);
return a;
}
And then:
int number = "123".ToInt();
Edit
Or you can pass integer as out parameter:
public static bool ToInt(this string v, out int a)
{
return int.TryParse(v, out a);
}
usage:
int number = 0;
"123".ToInt(out number);
Upvotes: 7
Reputation: 1989
Have you tried using a safe cast and doing a null-coalescing check in a single line?
SeasonFromYear = seasonFromYear as int ?? default(int);
Upvotes: 1
Reputation: 31610
Try:
int.TryParse(sessionFromYear, out SessionFromYear)
If SessionFromYear
can be a property just create a method that will do what you need to do - e.g.:
public int ParseInt(string input)
{
int value;
int.TryParse(input, out value);
return value;
}
and then you can use this method all over the place like this:
SessionFromYear = ParseInt(sessionFromYear);
if you want to make it really fancy you could even create an extension method on the string class and then just do something like sessionFromYear.ToInt()
Upvotes: 1
Reputation: 149000
That's not necessary. If int.TryParse
fails, a
will be set to default(int)
. Just use:
int a;
int.TryParse(sessionFromYear, out a);
SeasonFromYear = a;
Or if you really want to do it in one line, you'd have to create you're own wrapper method:
public static int TryParseInline(string in) {
int a;
int.TryParse(sessionFromYear, out a);
return a;
}
...
sample.AddRange(Statistics.Select(player => new Stats
{
SeasonFromYear = Util.TryParseInline(seasonFromYear),
...
})
Upvotes: 4