Reputation: 23833
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.
Upvotes: 12
Views: 31338
Reputation: 86718
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);
Upvotes: 22
Reputation: 113402
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.
Upvotes: 4
Reputation: 11201
How about doing it this way
List<string[]> sList = new List<string[]> {new []{"A", "B"}};
List<object[]> oList = sList.Cast<object[]>().ToList();
Upvotes: 0
Reputation: 110111
OfType<string[]>
returns an IEnumerable<string[]>
, not a List<object[]>
.
Enuemrable.OfType
filters out any invalid casts. You may want to consider Enumerable.Cast
instead ,which will throw if you make a mistake. If string[]
doesn't inherit from object[]
(I honestly don't remember), you may need to call Enumerable.Select
to provide a conversion.
You definately need a Enumerable.ToList call in there somewhere.
Upvotes: 3