Reputation: 1796
I'm building a linq query based on form inputs from the user. I have a view that expects an IList of type "trace".
This approach may be entirely wrong, but I'm getting the following error with the below code
Error 7 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IList'. An explicit conversion exists (are you missing a cast?)
I don't understand this becuase I never cast traces as enumerable in the first pace.
Ultimately, I just want to query the traces entity and return a list to the view.
IList<trace> traces = new List<trace>();
//by users
if (form["reps"] != null)
{
List<string> reps = new List<string>(form["reps"].Split(','));
traces = traces.Where(s => reps.Contains(s.repslist));
}
//by start date
if (!String.IsNullOrWhiteSpace(form["homefrom"]))
{
DateTime sdate = Convert.ToDateTime(form["homefrom"]);
traces = traces.Where(t => t.tracedate >= sdate);
}
return PartialView("_tracescontainer", traces);
EDIT
I tried the below - everything compiles, no errors, in google inspector, the post shows pending without erroring out. I've waiting for about 10 minutes. When debugging, I step through and the step never gets to the line IList tracelist = traces.ToList();
There is no error, it just goes out of the breakpoint as though the operation is complete, but no results are sent to the browser.
IEnumerable<trace> traces = db.traces;
//by users
if (form["reps"] != null)
{
List<string> reps = new List<string>(form["reps"].Split(','));
traces = traces.Where(s => reps.Contains(s.repslist));
}
//by start date
if (!String.IsNullOrWhiteSpace(form["homefrom"]))
{
DateTime sdate = Convert.ToDateTime(form["homefrom"]);
traces = traces.Where(t => t.tracedate >= sdate);
}
IList<trace> tracelist = traces.ToList();
return PartialView("_tracescontainer", tracelist);
Upvotes: 0
Views: 2275
Reputation: 203820
Where
returns an IEnumerable
, not a List
. Since you don't actually need your traces
variable to be an IList
here, you should type it as an IEnumerable
to avoid the needless overhead of populating the results of your query into a list just so that you can iterate over that list and populate a new list.
If it's important to materialize the results of the query into a list at some later point in time, after you have finished constructing the query, then you can call ToList
on the IEnumerable
to build up a List
with the results.
On top of the above, it appears that your actual data source is an IQueryable
representing a query against a database, not an in memory collection. You should use IQueryable
as the type of your variable. This will build up a query, rather than the results of the query, so that after building that query you can request the filtered results from your database, rather than pulling your entire database table into memory and filtering it there.
Upvotes: 3