Convert linq query to string array - C#

﹥>﹥吖頭↗ 提交于 2019-12-22 01:53:23

问题


What is the most efficient way of converting a single column linq query to a string array?

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
    }

Note - x.Word is a string


回答1:


I prefer the lambda style, and you really ought to be disposing your data context.

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



回答2:


How about:

return list.ToArray();

This is presuming that x.Word is actually a string.

Otherwise you could try:

return list.Select(x => x.ToString()).ToArray();



回答3:


if you type it in Lambda syntax instead you can do it a bit easier with the ToArray method:

string[] list = db.Words.OrderBy(w=> w.Word).Select(w => w.Word).ToArray();

or even shorter:

return db.Words.OrderBy(w => w.Word).Select(w => w.Word).ToArray();


来源:https://stackoverflow.com/questions/1378801/convert-linq-query-to-string-array-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!