Skip to main content
 首页 » 编程设计

c#之格式化 ListT> 以连接字段

2024年02月23日14cmt

我已经查看了数百个关于 SO 的类似问题,但没有找到我的答案。如果之前有人问过这个问题,请接受我的歉意。

我有一个 SQL 数据库,其中分别包含一列城市和一列州。我使用 Entity Framework 作为我的 DAL,在我的 BLL 中有很多 LINQ 来格式化、移动东西等。我的 UI 上有一个下拉菜单,它当前接受来自方法的 ToList()在我的 BLL 中一切正常,但我需要更改此方法以返回以逗号分隔的城市和州。到目前为止我有这个(这是行不通的!):

public static List<char> 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 { c.CityName, c.State }; 
        var cities = query.Select(i => i.CityName).Aggregate((i, j) => i + delimiter + j); 
        return cities.ToList();   
    } 
} 

我已经尝试过许多 LINQ 变体,但我显然没有得到正确的结果。任何人都可以提供一些帮助吗?一如既往,不胜感激:)

编辑 1:我希望该方法的输出是一个由逗号和空格分隔的串联城市名称和州的列表;例如:

Miami, Florida 
Key West, Florida 
New York, New York 
Boston, Massachusetts 

在我的示例中,输入只是相关国家/地区的 ISO-Alpha2 代码:“美国”。这可能是英国的“GB”或法国的“FR”或德国的“DE”。

请您参考如下方法:

编辑:删除匿名类型 编辑: 在定界符声明中添加了空格,使其略有不同 :-) ", "

希望我没有误解你的问题,但你可以通过在查询的返回值中添加定界符来添加如下操作:

public static List<string> 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 c.CityName + delimiter + c.State ;             
        return query.ToList(); 
    } 
} 

这将创建一个字符串类型的列表