views:

78

answers:

2

I've currently got the following foreach loop:

List<SearchResult> searchResults = new List<SearchResult>();
foreach (Transmission trans in Results)
{
    searchResults.Add(new SearchResult(trans));
}
return searchResults;

And I'd like to convert this to a Linq expression, I've tried the following which looks like it achieve the same thing in linq to me:

return Results.Select(x => new SearchResult(x)).ToList();

However when executed I get the following error:

System.InvalidCastException: Object must implement IConvertible.

I think I understand the gist of that error but the issue I have is that I'm not actually trying to convert the Transmission Objects in the Results collection to SearchResult objects but instead to return a list of SearchResult objects, a SearchResult object being intialized like so:

Transmission transmission = new Transmission(...);
SearchResult result = new SearchResult(trans);

Any help on this would be great, I've been tearing my hair out!

EDIT: As per comments here is the full method stub:

        public IQueryable<Transmission> Results
    {
        get;
        set;
    }

        public virtual IEnumerable<SearchResult> ResultsNetwork
    {
        get
        {
            List<SearchResult> searchResults = new List<SearchResult>();
            foreach (Transmission trans in Results)
            {
                searchResults.Add(new SearchResult(trans));
            }
            return searchResults;
        }
    }
+1  A: 

Its hard to guess what you are trying to cast (you need to show your method signature, as well as a blurb showing how you convert Transmissions to SearchResult)

However and easier way to do it:

return Results.ConvertAll(x=> new SearchResult(x));
Nix
Can someone please explain why the down vote?
Nix
+1  A: 

I get the impression that Results is a collection of object, so Select is defining x as object, but you want it to be Transmission.

Try either of these options:

return Results.Cast<Transmission>().Select(x => new SearchResult(x)).ToList();
return Results.OfType<Transmission>().Select(x => new SearchResult(x)).ToList();

Cheers.

Enigmativity