views:

141

answers:

3
var candidates = (from l in db.GetLeads(lat, lon, role, radius + 10)
                  orderby l.Distance
                  select l);
        return (List<CandidateResult>)candidates;
+5  A: 

If I understand your question correctly, you can use the Cast extension method, i.e.:

return candidates.Cast<CandidateResult>();
veggerby
I'm getting a message that says "Cannot implicitly convert type 'System.Linq.IQueryable<CandidateResult>' to 'System.Collections.Generic.List<CandidateResult>'. Any ideas?
Chad
+1  A: 

What about:

var candidates = (from l in db.GetLeads(lat, lon, role, radius + 10)
                  orderby l.Distance
                  select l).ToList();
Konamiman
+3  A: 

Well, your "candidates" variable isn't a List<T> - it's an IEnumerable<T> for some T.

However, List<T> isn't variant in T even in C# 4 (as it's a class, and classes are invariant; and also because it uses T in both an input and an output position).

Your simplest solution is to get the right type of sequence to start with and then call ToList:

var candidates = (from l in db.GetLeads(lat, lon, role, radius + 10)
                  orderby l.Distance
                  select (CandidateResult) l);
return candidates.ToList();

You can call Cast instead if you want, as shown below but in this particular case I don't think it makes it any nicer.

var candidates = (from l in db.GetLeads(lat, lon, role, radius + 10)
                  orderby l.Distance
                  select l);
return candidates.Cast<CandidateResult>()
                 .ToList();

Note that when you're only really doing one thing (ordering in this case) it's often simpler not to use query expressions, e.g.

return db.GetLeads(lat, lon, role, radius + 10)
         .OrderBy(l => l.Distance)
         .Cast<CandidateResult>()
         .ToList();
Jon Skeet
Tried the first one and got a "Cannot convert type'x.x.GetLeadsResult' to 'x.x.CandidateResult'. Does this mean that my types are not compatible, or am I missing something?
Chad
Yes, it means your types aren't compatible. What are the two types like, and how do you want to convert between them?
Jon Skeet
One type is the result of a UDF in SQL. I'm using linq to get the result, but I need to pass it from my repository back to the controller (MVC). So I added a type to my Model with the same properties / types. Any suggestions?
Chad
You can't convert from one type to another just because they've got the same properties. I suggest you add a constructor to create a `CandidateResult` from a `GetLeadsResult`.
Jon Skeet