15

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

3 Answers 3

36

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I like to give the gc a workout! - just kidding - this is a very good point. Thanks.
8

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 Comments

The first way gives this error - Cannot implicitly convert type 'AnonymousType#1[]' to 'string[]'. The second method works! Thanks!
Skip the new {} in your select and you won't have to unpack the anonymous type, you'll just have a string (assuming Word is a character column).
@tvanfosson, What does it mean to "unpack an anonymous type"? (I'm assuming an edit has been made to this answer, because I no longer see any new {}.)
4

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

2 Comments

both give error - Cannot implicitly convert type 'Word[]' to 'string[]'
Corrected it, missed the .Word bit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.