linq查询到List <string>的语法

Mal*_*Man 12 linq string casting nvarchar

我想做这样的事......

public static List<string> GetAttachmentKeyList()
{
    DataClassesDataContext dc = new DataClassesDataContext();

    List<string> list = from a in dc.Attachments
        select a.Att_Key.ToString().ToList();

    return list;
}
Run Code Online (Sandbox Code Playgroud)

Visual Studio说......

无法将类型'System.Linq.IQueryable>'隐式转换为'System.Collections.Generic.List'.存在显式转换(您是否错过了演员?)

什么是正确的语法???

Bri*_*haw 20

试一试

public static List<string> GetAttachmentKeyList()
{
    DataClassesDataContext dc = new DataClassesDataContext();

    List<string> list = ( from a in dc.Attachments
                          select a.Att_Key.ToString() ).ToList();

    return list;
}
Run Code Online (Sandbox Code Playgroud)

  • +1:是的,在原始样本中,`.ToList()`在`ToString()`返回的字符串上被调用,所以linq表达式被评估为 - _something like_ - `IEnumerable <List <char >>`,而不是`列表<字符串>` (3认同)

Ped*_*sta 12

试试这个,

public static List<string> GetAttachmentKeyList()
{
    DataClassesDataContext dc = new DataClassesDataContext();

    return dc.Attachments.Select(a=>a.Att_Key).ToList();
}
Run Code Online (Sandbox Code Playgroud)