开发者

filter array with integer values

i have a str开发者_如何学编程ing 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#?


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);


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.


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


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜