c# - 使用 LINQ for Dropdown 返回串联字符串

标签 c# linq

这是这个问题的后续内容:Format List<T> to concatenate fields 。答案是正确的,但回答后我想返回 List从方法中,这样它就可以被重复使用。我到目前为止,但这不正确(因为我知道 Iqueryable 不正确,它只是防止 AnonymousType 错误):

public static IQueryable GetCitiesInCountryWithState(string isoalpha2)
    {
        const string delimiter = ", ";
        using (var ctx = new atomicEntities())
        {
            var query = (from c in ctx.Cities
                        join ctry in ctx.Countries on c.CountryId equals ctry.CountryId
                        where ctry.IsoAlpha2 == isoalpha2
                        select new
                                   {
                                       CityId = c.CountryId,
                                       CityName = c.CityName + delimiter + c.State
                                   });
            return query;
        }
    }

我希望能够返回 List<string>在这里(如果可能的话),然后在 UI 上执行类似的操作:

ddlCity.DataSource = GetCitiesInCountryWithState(Session["BusinessCountry"].ToString());
            ddlCity.DataTextField = "CityName";
            ddlCity.DataValueField = "CityId";
            ddlCity.DataBind();

我已经尝试了各种方法,但没有运气。我知道我已经很接近了 - 但需要帮助!感谢您的帮助:)

最佳答案

您无法返回匿名类型,编译器无法维护类型安全。

所以如果你定义一个类

class City {
  public int CityId {get; set;}
  public string CityName {get; set;}
}

将您选择的新 {} 替换为选择新城市{},并返回 List 或 IQueryable 您应该没问题。

关于c# - 使用 LINQ for Dropdown 返回串联字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5628524/

相关文章:

c# - 将 IQueryable<T> 或 LINQ 查询转换为唯一字符串

sql - 我如何将此 SQL 代码转换为 LINQ?

c# - 删除列表中最后一次出现的字符串

c# - 层次结构不会在 View 中更新

c# - 在 Visual Web Developer 2010 Express 中运行 "working"Web 应用程序时出错

mysql - 在 MVC 中将参数从 View 传递到操作

linq - 在 PowerShell 中调用静态通用 LINQ 扩展方法

c# - 是一个静态方法,对于不同的调用使用相同的变量

c# - 在c#中获取操作系统语言

c# - 样式问题 : LINQ or XPath to read in XML nodes