I have a table that has multiple fields which I just need one field. The table called ZipCompare. I usually use IQueryable<> as returned type of a linq query. But for the following code, an error comes out said "can not implicitly convert type System.Linq.IQueryable<AnonymousType#1>
to ZipCompare. Then what return type I should use? I use this function to fill the dropdownlist control My code is :
public IQueryable<ZipCompare> GetStates()
{
VettingDataContext dc = new VettingDataContext(_connString);
dc.DeferredLoadingEnabled = true;
var query = (from c in dc.ZipCompares
select new { States = c.State }).Distinct();
return query;
}
Front end code:
ddl_BilState.DataSource = zipDAL.GetStates();
ddl_BilState.DataTextField = "States";
ddl_BilState.DataValueField = "States";
ddl_BilState.DataBind();
This is a .net web application, I write in c#.
Look at your query:
var query = (from c in dc.ZipCompares
select new { States = c.State }).Distinct();
That isn't selecting a ZipCompare
- it's selecting an anonymous type. It's not clear what you are trying to do, but if you want to return an IQueryable<ZipCompare>
your select
clause will need to be select a ZipCompare
.
If you don't want to return a ZipCompare... well, in this case it looks like you don't need an anonymous type. Just use:
var query = (from c in dc.ZipCompares
select c.State).Distinct();
Or rather more succinctly:
return dc.ZipCompares.Select(c => c.State).Distinct();
You then change your data binding to bind to the value itself (use "." as the field perhaps? Or perhaps the empty string? Not sure).
return IEnumerable<TypeOfStateProperty>
, and change your query not to use an anonymous type. For instance if State
is a StateEnum
value:
public IEnumerable<StateEnum> GetStates()
{
VettingDataContext dc = new VettingDataContext(_connString);
dc.DeferredLoadingEnabled = true;
var query = (from c in dc.ZipCompares select c.State ).Distinct();
return query;
}
Perhaps you want to return a List of string? State looks like a string...
Change your return type to List<string>
and do this:
foreach(var item in query)
{
myList.Add(item.States);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.