'return in if statement throws conversion error
I will apologize in advance for the long post. Just trying to give you all the information I have.
I have an if
statement in a method that looks like this:
var comparison = await SystemService.SearchCount();
var fileExporter = Configure();
var fileName = "SearchResults"
if (defaultValue <= comparison)
{
var result = SearchResult.Rows.Where(s => VSR.Any(s2 => s2.ID == s.Values.FirstOrDefault()));
var records = SearchResult.Rows.ToList();
await Task.Yield();
return fileExport.ToCsv(records, fileName);
}
The error that I am getting is the following error:
cannot convert from '
System.Collections.Generic.List<SearchRows>
' to 'System.Collections.Generic.IList<SearchResults>
'
I tried to change the return to explicitly cast to IList
like this:
return fileExport.ToCsv((IList<SearchResults>)records, fileName);
This will let it build in Visual Studio but it throws an InvalidCastException when I run it and look at the developer tools:
System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List[SearchRow] to type System.Collections.Generic.IList[SearchResult].
What am I missing here? I don't see an issue at all with the code.
The SearchResults model is a listing of the records to be returned (Id, name etc)
The SearchRows model serves as a wrapper for the columns and rows (I didn't name these they came in with the legacy code)
Solution 1:[1]
records
is of type List<SearchRow>
, which is not compatible with the type List<SearchResult>
, you either have to convert the SearchRows
to SearchResults
(e.g. via a Select
) or alter the type accepted by ToCSV
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nick Bailey |