Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List<string[]> to List<object[]> Conversion

All, have I gone mental (this is not the question). I want to convert List<string[]> to List<object[]>

List<string[]> parameters = GetParameters(tmpConn, name);
List<object[]> objParams = parameters.OfType<object[]>();

this is not working, but unless I have forgotten something a conversion using this method should be possible (no Lambdas needed)?

Thanks for your time.

like image 495
MoonKnight Avatar asked Jun 22 '12 18:06

MoonKnight


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C and C++ meaning?

C is a function driven language because C is a procedural programming language. C++ is an object driven language because it is an object oriented programming. Function and operator overloading is not supported in C. Function and operator overloading is supported by C++. C is a function-driven language.


2 Answers

You want to use something like:

List<object[]> objParams = parameters.OfType<object[]>().ToList();

or in C# 4.0, just

List<object[]> objParams = parameters.ToList<object[]>();

or

List<object[]> objParams = parameters.ConvertAll(s => (object[])s);
like image 125
Gabe Avatar answered Sep 28 '22 03:09

Gabe


Because of array covariance, in .NET 4.0, you can just do:

// Works because:
// a) In .NET, a string[] is an object[]
// b) In .NET 4.0, an IEnumerable<Derived> is an IEnumerable<Base>              
var result = parameters.ToList<object[]>();

But note that you wouldn't be able to mutate those arrays with anything other than strings (since array covariance isn't truly safe).

If you want truly flexible writable object arrays, you can do:

var result = parameters.Select(array => array.ToArray<object>())
                       .ToList();

(or)

var result = parameters.ConvertAll(array => array.ToArray<object>());

Then you could replace the elements of each inner array with instances of pretty much any type you please.

like image 24
Ani Avatar answered Sep 28 '22 04:09

Ani