List box conversion to array int - c#

I'm trying to convert a listbox to an array:
var modarray = listBox1.Items.Cast<String>().ToArray();
but then I also need to use an int array so I tried the following:
int[] arr = modarray.Cast<int>().ToArray();
I get an error that suggests that is not possible to convert the array. Can anybody help me please?

Try this:
int[] arr = modarray.Select(int.Parse).ToArray();
This will use the int.Parse() method for each of the strings in the original array to create a new integer array.

Try this instead :
int[] arr = modarray.Select(I => Convert.ToInt32(I)).ToArray();

.Cast<int>() is like foreach (var i in list) yield return (int)i;
Which if your items are strings underneath will fail.
I believe you need: int[] arr = modarray.Select(s => Int32.Parse(s)).ToArray();

Related

Convert C# Dictionary to multidimensional array

I am trying to convert Dictionary<string, string> to multidimensional array.
The items inside multidimentional array should be in quotes.
So far I get this ["[mary, online]","[alex, offline]"].
But the output should be something like [["mary", "online"], ["alex", "offline"]]. Please help.
public void sendUpdatedUserlist(IDictionary<string, string> message)
{
string[] array = message
.Select(item => string.Format("[{0}, {1}]", item.Key, item.Value))
.ToArray();
}
If you insist on 2d array (string[,], not jagged string[][]) you can create the array and fill it row by row:
string[,] array = new string[message.Count, 2];
int index = 0;
foreach (var pair in message) {
array[index, 0] = pair.Key;
array[index++, 1] = pair.Value;
}
string.Format isn't going to return an array, you're close, but what you want is to "select" an actual array. Something like this:
var arr = dict.Select(kvp => new[] { kvp.Key, kvp.Value }).ToArray();
this is going to return type of string[][], which is technically a jagged array (unlike a true 2D array string[,] in that each dimension doesn't have to be the same size) unlike the one-dimensional string[] you have declared in your sample code.
If you truly need a 2D array, you can't really do that with LINQ and .ToArray(), you'll have to populate it yourself with a loop.

How to convert list of objects with two fields to array with one of them using LINQ

It's hard for me to explain, so let me show it with pseudo code:
ObjectX
{
int a;
string b;
}
List<ObjectX> list = //some list of objectsX//
int [] array = list.Select(obj=>obj.a);
I want to fill an array of ints with ints from objectsX, using only one line of linq.
You were almost there:
int[] array = list.Select(obj=>obj.a).ToArray();
you need to just add ToArray at the end
The only problem in your code is that Select returns IEnumerable.
Convert it to an array:
int[] array = list.Select(obj=>obj.a).ToArray();

cast an Object[] array to an Integer Array

What is the easiest way to cast an object array to an integer array?
ArrayList al = new ArrayList();
object arrayObject = al.ToArray();
int[]arrayInteger = ?
Thanks
If you import System.Linq namespace you can do this:
int[] arrayInteger = a1.Cast<int>().ToArray();
Use int[]arrayInteger = (int[])al.ToArray(typeof(int));
But unless you are using .Net 1.1, user a List<int> instead.
(object[] eventTypes) Assuming eventTypes are all objects with integer values, this would do it:
int[] eventTypeIDs = eventTypes.Select( Convert.ToInt32).ToArray();
You could use Array.ConvertAll
int[] intArray = Array.ConvertAll<object, int>(al.ToArray(), (o) => (int)o);
One thing to consider is since this is an object array all the values may not be int
This is the handy thing about ConvertAll as you can add simple conversion logic to catch errors.
Scenario:
ArrayList al = new ArrayList() { 1,"hello",3,4,5,6 };
int[] intArray = Array.ConvertAll<object, int>(al.ToArray(), (o) => { int val = -1; return int.TryParse(o.ToString(), out val) ? val : -1;});
This way we can perform a TryParse on the object to avoid any InvalidCastException due to bad data.
or
int[] intArray = object as int[];

Parse int[] from "1,2,3"

I have a multiselect dropdown called ID that submits ID=1,2,3 which I need parsed into an integer array to do a Contains() on in a filter method. At the moment I use:
string[] ids = Request["ID"].Split(',');
Which I don't really like because its slower to compare string than int. Any suggestions?
Request["ID"].Split(',').Select(x=>int.Parse(x)).ToArray();
Of course, this will throw if any of the resulting numeric strings are not "parseable" (does such a word exist?).
It depends on how many times you will look up in the array if converting to ints are faster or the string comparison is faster.
HashSet<int> ids = new HashSet<int>(from s in Request["ID"].Split(',')
select int.Parse(s));
But probably the fastest if you have many id:s will be to create a HashSet<string>:
HashSet<string> = new HashSet<string>(string[] ids = Request["ID"].Split(','));
int[] ids = Request["ID"].Split(',').Select(Convert.ToInt32).ToArray();
First:
string[] arr = Request["ID"].Split(',')
Then:
Array.ConvertAll(arr, s => Int32.Parse(s));
Array.ConvertAll(arr, Int32.Parse);
arr.Select(s => Int32.Parse(s));
arr.Select(Int32.Parse);
Then:
new HashSet<int>(result);
(the most fast container to perform Contains())
See also:
Convert string[] to int[] in one string of code using LINQ
Which one is faster in processing and conversion int.Parse(), int.TryParse(), Convert.Int32()
If you don't have linq, you can:
string[] ids = Request["ID"].Split(',');
int[] items = new int[ids.Length];
for(int i = 0; i<ids.Length; i++)
{
items[i] = int.Parse(ids[i]);
}

converting list<int> to int[]

Is there builtin method that would do this or do I always have to manually create a new array and then fill it up with a foreach loop
list.ToArray()
List<int> list = ...
...
int[] array = list.ToArray();
You can also use the CopyTo method :
int[] array = new int[list.Count];
list.CopyTo(array);

Categories

Resources