开发者

Converting Foreach Loop to Linq and getting error

开发者 https://www.devze.com 2023-01-22 14:44 出处:网络
I\'ve currently got the following foreach loop: List<SearchResult> searchResults = new List<SearchResult>();

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 Re开发者_如何学Pythonsults.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;
        }
    }


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.


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消