Convert Foreach loop to Linq and get error

Currently, I 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 would like to convert this to a Linq expression, I tried the following, which looks like it is doing the same thing in linq for me:

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

However, when I execute, I get the following error:

System.InvalidCastException: Object must implement IConvertible.

I think I understand the essence of this error, but the problem is that I'm not really trying to convert the transfer objects into a collection of results into SearchResult objects, but instead return a list of SearchResult objects, the so-called SearchResult object:

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

Any help on this would be great, I tore my hair out!

EDIT: According to the comments, here is the complete stub method:

        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;
        }
    }
+3
2

, Results object, Select x object, , Transmission.

:

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

.

+2

, ( , , , Transmissions SearchResult)

:

return Results.ConvertAll(x=> new SearchResult(x));
+1

Source: https://habr.com/ru/post/1771925/


All Articles