user583126
user583126

Reputation: 701

filter array with integer values

i have a string array with values { "01.0", "01.4", "01.5", "0.20", "02.5", "02.6", "03.0", "03.2" } how do i filter integer values (1,2,3) from this using C#?

Upvotes: 0

Views: 2167

Answers (4)

Mirko
Mirko

Reputation: 4282

var array = new[] { "01.0", "01.4", "01.5", "02.0", "02.5", "02.6", "03.0", "03.2" };
int foo;
var integers = (from a in array where decimal.Remainder(decimal.Parse(a), 1) == 0 select (int)decimal.Parse(a));
foreach (var integer in integers)
{
    Console.WriteLine(integer);
}
Console.ReadLine();

Upvotes: 0

Jon
Jon

Reputation: 437356

Parse the strings to floats, select only those that are integers and cast off duplicate entries:

var input = new[] { "01.0", "01.4", "01.5", "0.20", "02.5", 
                    "02.6", "03.0", "03.2" };
var integers = input.Select(i => 
                         double.Parse(i,
                         System.Globalization.CultureInfo.InvariantCulture))
                    .Where(d => d == (int)d)
                    .Distinct().ToArray();

Answer edited to take into account the OP's later comments.

Upvotes: 3

NerdFury
NerdFury

Reputation: 19214

First do a select to convert the string values to decimals. Then use the Remainder function to find which values have a zero remainder when divided by 1. That should get you only integer values.

var array = new[]{"01.0", "01.4", "01.5", "02.0", "02.5", "02.6", "03.0", "03.2"};

array.Select(i => Decimal.Parse(i)).Where(d => Decimal.Remainder(d, 1) == 0);

Upvotes: 3

clamport
clamport

Reputation: 311

You can use int.Parse(array[here]), as long as your array is a string, or convertible to a string.

Upvotes: 0

Related Questions