将linq查询转换为字符串数组 - C#

14 c# linq arrays string casting

将单列linq查询转换为字符串数组的最有效方法是什么?

private string[] WordList()
    {
        DataContext db = new DataContext();

        var list = from x in db.Words
                   orderby x.Word ascending
                   select new { x.Word };

       // return string array here
    }
Run Code Online (Sandbox Code Playgroud)

注 - x.Word是一个字符串

tva*_*son 32

我更喜欢lambda风格,你真的应该处理你的数据上下文.

private string[] WordList()
{
    using (DataContext db = new DataContext())
    {
       return db.Words.Select( x => x.Word ).OrderBy( x => x ).ToArray();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢给gc锻炼一下! - 开玩笑 - 这是一个非常好的观点.谢谢. (2认同)

Dar*_*mas 7

怎么样:

return list.ToArray();
Run Code Online (Sandbox Code Playgroud)

这假设x.Word实际上是一个字符串.

否则你可以尝试:

return list.Select(x => x.ToString()).ToArray();
Run Code Online (Sandbox Code Playgroud)