Select Parsed Int, If String Was Parseable to Int

Select parsed int, if string was parseable to int

It's hard to do that in query syntax, but it's not too bad in lambda syntax:

var ints = strings.Select(str => {
int value;
bool success = int.TryParse(str, out value);
return new { value, success };
})
.Where(pair => pair.success)
.Select(pair => pair.value);

Alternatively, you may find it worth writing a method which returns an int?:

public static int? NullableTryParseInt32(string text)
{
int value;
return int.TryParse(text, out value) ? (int?) value : null;
}

Then you can just use:

var ints = from str in strings
let nullable = NullableTryParseInt32(str)
where nullable != null
select nullable.Value;

What is the best way to check if a string can be parsed into an int array?

I could put a Try..Catch around it but I am generally adverse to controlling logic flow by exceptions

Good attitude. If you can avoid the exception, do so.

A number of answers have suggested

int myint;
bool parseFailed = SearchTerm.Split(',')
.Any( s => !int.TryParse(s, out myint));

Which is not bad, but not great either. I would be inclined to first, write a better helper method:

static class Extensions
{
public static int? TryParseAsInteger(this string s)
{
int j;
bool success = int.TryParse(s, out j);
if (success)
return j;
else
return null;
}
}

Now you can say:

bool parseFailed = SearchTerm.Split(',')
.Any( s => s.TryParseAsInteger() == null);

But I assume that what you really want is the parsed state if it can succeed, rather than just answering the question "would a parse succeed?" With this helper method you can say:

List<int?> parse = SearchTerm.Split(',')
.Select( s => s.TryParseAsInteger() )
.ToList();

And now if the list contains any nulls, you know that it was bad; if it doesn't contain any nulls then you have the results you wanted:

int[] results = parse.Contains(null) ? null : parse.Select(x=>x.Value).ToArray();

How do I convert a String to an int in Java?

String myString = "1234";
int foo = Integer.parseInt(myString);

If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which you can handle:

int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
foo = 0;
}

(This treatment defaults a malformed number to 0, but you can do something else if you like.)

Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)

Int.Parse in Linq Expression

You can't use int.parse in where. You can rewrite your query like this:

var list = (from x in
(
from inv in m.INVs
join l in m.LIBs on inv.MESC equals l.MESC
join o in m.OUTs on inv.MESC equals o.MESC
join t in m.TRANs on inv.MESC equals t.MESC
where t.TYPE == "60" && t.QTY!=""
select new
{
l.MESC,
l.LINE_NO,
l.UNIT_LINE,
Description = l.DES + " " + l.PART_NO,
inv.NEW_QTY,
o.PJ,
o.DATE,
o.QTY,
o.QTY_REC,
TranQty = t.QTY,
tranDate = t.DATE

}
).ToList()
group x by
new
{
x.MESC,
x.LINE_NO,
x.UNIT_LINE,
x.Description,
x.NEW_QTY,
x.PJ,
x.DATE,
x.QTY,
x.QTY_REC
}
into g
select new
{
QTY_Consum_1 = g.Where(c => int.Parse(c.tranDate) >= cuDate && int.Parse(c.tranDate) <= endDate).Sum(d => int.Parse(d.TranQty)),
g.Key.MESC
}
).ToList();

Call .ToList() method, then use int.Parse(variable).

Have a nice day.

Identify if a string is a number

int n;
bool isNumeric = int.TryParse("123", out n);

Update As of C# 7:

var isNumeric = int.TryParse("123", out int n);

or if you don't need the number you can discard the out parameter

var isNumeric = int.TryParse("123", out _);

The var s can be replaced by their respective types!

Is it possible to convert the String value we are getting by intent via get string extra into integer with Integer.parseInt(String)

This happens because you are trying to parse a String that does not match with an integer, in order to avoid this, use NumberFormatException thrown by parseInt

NumberFormatException - if the string does not contain a parsable integer.

Also, "19" is the name of the extra you use to putExtra in your intent, right?

String a=qw.getStringExtra("19");  // 19 is the extra name, right???
int b = 0;
try {
b= Integer.parseInt(a);
} catch (NumberFormatException e) {
// tell error because extra string is not an integer number
}

int.Parse, Input string was not in a correct format

If you're looking to default to 0 on an empty textbox (and throw an exception on poorly formatted input):

int i = string.IsNullOrEmpty(Textbox1.Text) ? 0 : int.Parse(Textbox1.Text);

If you're looking to default to 0 with any poorly formatted input:

int i;
if (!int.TryParse(Textbox1.Text, out i)) i = 0;

Easy way to avoid string addition in C#

If you want to use spesific variables, you can code this use case like this

void Add()
{
int aInt, bInt, cInt, dInt, eInt, fInt;
int.TryParse(a, out aInt);
int.TryParse(b, out bInt);
int.TryParse(c, out cInt);
int.TryParse(d, out dInt);
int.TryParse(e, out eInt);
int.TryParse(f, out fInt);
int total = aInt + bInt + cInt + dInt + eInt + fInt;
}

If you want to use more extendible code, you should use collection

void Add()
{
int total = 0;
foreach (var c in myStrCollection)
{
int.TryParse(c, out int a);
total += a;
}
}

int.TryParse will try to convert the string to int. If it cannot convert, variable a will be 0 as default. 0 is ineffective element for addition. If this method is multiplication, you should change the method like this.

void Multiply()
{
int total = 0;
foreach (var c in myStrCollection)
{
bool s = int.TryParse(c, out int a);
if(!s) a = 1;
total *= a;
}
}


Related Topics



Leave a reply



Submit