简体   繁体   中英

convert List<Object> to System.Array[]

I have an Array

Array[] Values;

I sorted that Array using this code

List<Object> val= new List<Object>();

foreach (var arr in Values)
{
    if (arr.GetValue(1, 9).Equals("Impact"))
        val.Add(arr);
}
foreach (var arr in Values)
{
    if (arr.GetValue(1, 9).Equals("Critical"))
        val.Add(arr);
}
foreach (var arr in Values)
{
    if (arr.GetValue(1, 9).Equals("High"))
        val.Add(arr);
}
foreach (var arr in Values)
{
    if (arr.GetValue(1, 9).Equals("Medium"))
        val.Add(arr);
}
foreach (var arr in Values)
{
    if (arr.GetValue(1, 9).Equals("Low"))
        val.Add(arr);
}

now I have to convert the List val back to System.Array[] .

I have tried doing this using Values = val.ToArray(); but it is giving compilation error that object[] cannot be converted to System.Array[] implicitly.

Is there any way to convert List<object> to System.Array[] explicitly ?

Or is there any other way to sort Values ?

Use a little bit more LINQ Select will help you do the trick:

Array[] Values = val.Select(x => (Array)x).ToArray();

Note: every x must be convertible to Array .

That said, Array itself is already an array. Array[] seems to be Array of Arrays to me and the data types of the elements are not strongly typed.

Array a = new int[10]; //this is ok
Array b = new string[10]; //this is also ok

Thus, your Array[] may contain any strongly-typed arrays. {int[], string[], double[]} and so on...

Unless it is what you really want, it seems to be not so safe design - IMHO.

In my opinion it is a design issue. Why do you declare the val-List as an Object-List and not an Array-List in the first place?

So, why don't you use:

List<Object> val= new List<Array>();

instead of

List<Object> val = new List<Object>();

That way, an easy ToArray() call should work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM