The problem with TryParse()
is that it's not an implementation of any interface: you'll either need to use reflection to find the method, or (simpler), just provide a conversion delegate.
Then you can do something like this, with a 2D array (or actually, arrays of any number of dimensions:
string[,] raw = { { "1" , "2" , } ,
{ "3" , "X" , } ,
{ "5" , "6" , } ,
} ;
int?[] converted = raw.Cast<string>()
.Select( s => {
int value ;
bool parsed = int.TryParse( s , out value ) ;
return parsed ? (int?) value : (int?)null ;
})
.ToArray()
;
If your array is jagged, you'll need one more step:
string[][] raw = { new string[]{"1","2",} ,
new string[]{"3","X",} ,
new string[]{"5","6",} ,
} ;
int?[] converted = raw.Cast<string[]>()
.SelectMany( s => s )
.Select( s => {
int value ;
bool parsed = int.TryParse( s , out value ) ;
return parsed ? (int?) value : (int?)null ;
})
.ToArray()
;
Given your example:
var marketInputColl = new Collection<MarketInput>();
foreach (object o in marketInputs)
{
MarketInput mktInput;
if (ExcelCache.TryGetCache<MarketInput>(o.ToString(), out mktInput))
marketInputColl.Add(mktInput);
}
We can take the same basic approach:
Collection<MarketInput> collection = new Collection<MarketInput>(
marketInputs
.Cast<object>()
.Select( o => o.ToString() )
.Select( s => {
MarketInput v ;
bool parsed = ExcelCache.TryGetCache<MarketInput>( s , out v ) ;
return parsed ? v : null ;
})
.Where( x => x != null )
.ToList()
) ;