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();
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();
How to Convert a String into Integer Array in C#
Try this,
static void Main(string[] args)
{
int[] num;
int accum = 0;
string input = Console.ReadLine();
num = Array.ConvertAll(input.Split(','), int.Parse);
for (int i = 0; i < num.Length; i++)
accum ^= num[i];
Console.WriteLine(accum);
}
Or by using Linq, just replace as follows, and you should need to use System.Linq
namespace.
num = input.Split(',').Select(int.Parse).ToArray();
.NetFiddle : https://dotnetfiddle.net/bahpg9
C# LINQ: How is string([1, 2, 3]) parsed as an array?
The order is the order that you specify. So input.Skip(2)
skips the first two strings in the array, so only the last remains which is 3
. That can be parsed to an int
. If you remove the Skip(2)
you are trying to parse all of them. That doesn't work because the commas are still there. You have splitted by white-spaces but not removed the commas.
You could use line.Trim('[', ']').Split(',');
and int.TryParse
:
string line = "[1, 2, 3]";
string[] input = line.Trim('[', ']').Split(',');
int i = 0;
int[] num = input.Where(s => int.TryParse(s, out i)) // you could use s.Trim but the spaces don't hurt
.Select(s => i)
.ToArray();
Just to clarify, i have used int.TryParse
only to make sure that you don't get an exception if the input contains invalid data. It doesn't fix anything. It would also work with int.Parse
.
Update: as has been proved by Eric Lippert in the comment section using int.TryParse
in a LINQ query can be harmful. So it's better to use a helper method that encapsulates int.TryParse
and returns a Nullable<int>
. So an extension like this:
public static int? TryGetInt32(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
Now you can use it in a LINQ query in this way:
string line = "[1, 2, 3]";
string[] input = line.Trim('[', ']').Split(',');
int[] num = input.Select(s => s.TryGetInt32())
.Where(n => n.HasValue)
.Select(n=> n.Value)
.ToArray();
Linq OrderBy issue when converting string to int with space
you can avoid empty strings by first filtering them out. i.e.
objStudentList = objStudentList.Where(a => !string.IsNullOrEmpty(a.Pincode))
.OrderBy(a => int.Parse(a.Pincode)).ToList();
However, if you want to keep the Student
objects that have an empty string but rather replace their Pincode
property with "0"
you can try this:
objStudentList = objStudentList.OrderBy(a => string.IsNullOrEmpty(a.Pincode) ? int.Parse("0") : int.Parse(a.Pincode))
.ToList();
Sum any strings that are numbers from string array using LINQ
You can not combine Where
and Select
, but you can change it to parse string only once
var sum = array
.Select(text => (IsNumber: int.TryParse(text, out var number), Number: number))
.Where(value => value.IsNumber)
.Sum(value => value.Number);
Another approach to do everything in the Sum
var sum = array.Sum(text => int.TryParse(text, out var number) ? number : 0);
Actually you can unite the Where and Select clauses, only because you calculating a sum.
For text, which is not valid number return 0.
var sum = array
.Select(text => { int.TryParse(text, out var number); return number; })
.Sum();
You can go further and create an extension method for string
. Which will make such expressions simpler
public static int ParseOrDefault(string value)
{
int.TryParse(text, out var number);
return number;
}
var sum = array.Sum(value => value.ParseOrDefault());
Related Topics
Use Task.Run() in Synchronous Method to Avoid Deadlock Waiting on Async Method
Ef Data Context - Async/Await & Multithreading
Looking for a Command Line Argument Parser for .Net
Find the Next Tcp Port in .Net
Calling a Method in Parent Page from User Control
Find Methods That Have Custom Attribute Using Reflection
When Using a Settings.Settings File in .Net, Where Is the Config Actually Stored
Read Appsettings JSON Values in .Net Core Test Project
Cssrewriteurltransform with or Without Virtual Directory
Connect to Active Directory via Ldap
How to Get a List<String> Collection of Values from App.Config in Wpf
Ilookup<Tkey, Tval> VS. Igrouping<Tkey, Tval>
Explicit Conversion Operator Error When Converting Generic Lists
How to Load All Assemblies from Within Your /Bin Directory
JSONconvert.Serializeobject Always Return {} in Xamarinforms
How to Show a Image in Database in the Image Control of ASP.NET