Andrew
Andrew

Reputation:

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

Upvotes: 15

Views: 67944

Answers (3)

Robban
Robban

Reputation: 6802

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

Upvotes: 4

tvanfosson
tvanfosson

Reputation: 532435

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

Upvotes: 36

Daren Thomas
Daren Thomas

Reputation: 70314

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

Upvotes: 8

Related Questions