Convert String[] to Int[] in One Line of Code Using Linq

Convert string[] to int[] in one line of code using LINQ

Given an array you can use the Array.ConvertAll method:

int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));

Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:

int[] myInts = Array.ConvertAll(arr, int.Parse);

A LINQ solution is similar, except you would need the extra ToArray call to get an array:

int[] myInts = arr.Select(int.Parse).ToArray();

convert string[] to int[]

var values = new string[] { "1", "2", "3" };
values.Select(x => Int32.Parse(x)).ToArray();

Convert a string in a List int using LINQ (cleaner way)

public class ParsesStringsToIntsWithLinq
{
public IEnumerable<int> Parse(string input)
{
var i = 0;
return (from segment in input.Split(',')
where int.TryParse(segment, out i)
select i);
}
}

[TestClass]
public class Tests
{
[TestMethod]
public void IgnoresNonIntegers()
{
var input = "1,2,3,4,s,6";
var output = new ParsesStringsToIntsWithLinq().Parse(input);
Assert.IsTrue(output.SequenceEqual(new []{1,2,3,4,6}));
}
}

It doesn't return a List<int> but I have to draw the line somewhere. You can make a list out of it.

Convert string to int for ordering using LINQ

I am one of the developers of LightSpeed.

The LINQ provider in LightSpeed 3.11 RTM doesn't support Convert.ToInt32. However we have now added support via a nightly release which is available for download now.

If you don't want to use the nightly release, you can achieve the result you want by dropping down to the Query Objects API and invoking the SQL CAST function directly. This will look something like:

Query query = new Query
{
Order = Order.By(Entity.Attribute("Number")
.Function("CAST", new LiteralExpression("INTEGER") { EmitInline = true }))
};

uow.Find<RfidTag>(query);

The reason for the rather verbose LiteralExpression for the cast type is that by default LightSpeed sends values to the database through parameters (to avoid SQL injection attacks). But for the CAST function the SQL engine needs to see CAST(Number, INTEGER) rather than CAST(Number, @p0) where p0 has the value "INTEGER". So you have to use an EmitInline expression, which bypasses parameterisation, rather than the more natural string literal.

Once again, though, the nightly release does support Convert.ToInt32 in LINQ so you only need to drop down to this level if you want to avoid taking a nightly build.

Parse/convert string array to int

I'd prefer to use dictionary in this case, but it might be handy for you to know as well that you can store values of different types using the object type. Later you'll have to do type conversion to use math operations

object[,] a = 
{
{"name song 1", 2},
{"name song 2", 5},
{"name song 3", 8}
};

var sum = 0;

for (int i = 0; i < a.GetLength(0); i++)
{
sum += Convert.ToInt32(a[i, 1]);
}

Console.WriteLine(sum);

If you are familiar with classes, you could reorganize your multi-dimensional array into single-dimensional, which makes code way more readable.

This approach is better than the previous one or the one that uses dictionary, since you'll have to modify less code when Song class extends into more properties

public class Song
{
public string Name { get; set; }

public int Value { get; set; }
}

class Program
{
static void Main(string[] args)
{
Song[] a =
{
new Song() { Name ="name song 1", Value = 2 },
new Song() { Name ="name song 2", Value = 5 },
new Song() { Name ="name song 3", Value = 8 },
};

var sum = 0;

for (var i = 0; i < a.Length; i++)
{
sum += a[i].Value;
}

Console.WriteLine(sum);
}
}

Convert string to int array using LINQ

This post asked a similar question and used LINQ to solve it, maybe it will help you out too.

string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ia = s1.Split(';').Select(n => Convert.ToInt32(n)).ToArray();

LINQ return value conversion failed from string to int

Try Convert.ToInt32(lc.LINECODE) or maybe due to 10.1 try Convert.ToDecimal(lc.LINECODE). There are more conversion methods here of the Convert class.

UPDATE #1

What seems a better solution is to forget the order at the DB side.

Instead before calling .ToList() call .OrderBy(item => Decimal.Parse(item.LINECODE)).

In VB.NET: .OrderBy(Function(item) Decimal.Parse(item.LINECODE))

UPDATE #2

@Keyur PATEL is right. I also suggested to forget the ordering at the DB side but missed that an extra call to .ToList() is needed.

So what should work looks like this:

_Result =
(
From lc As SLBLINECODE In DataManager.SlbContext.SLBLINECODES
Where lc.HIDDEN = 0
Order By lc.LINECODE
Select New With {
.LINECODE = lc.LINECODE,
.LINEDESCRIPTION = lc.LINECODE + " - " + lc.LINEDESCRIPTION
}
) _
.ToList() _
.OrderBy(Function(item) Decimal.Parse(item.LINECODE)) _
.ToList()


Related Topics



Leave a reply



Submit