简体   繁体   中英

Convert linq query to string array - C#

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

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();
    }
}

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM