views:

1407

answers:

4

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  A: 

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();
Robban
both give error - Cannot implicitly convert type 'Word[]' to 'string[]'
Corrected it, missed the .Word bit
Robban
+4  A: 

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();
Daren Thomas
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
A: 
from x in db.Words
orderby x.Word ascending
select x.Word;

return list.ToArray();

However I'd recommend you to return list instead. Returning arrays from method is not a wise thing.

Hasan Khan
Why is it not a wise thing to return an array?
Bob
Generally I'd agree that the List interface is to be preferred -- much easier to use -- you can insert into it easily, add to it, remove from the middle, all without writing the code to adjust the array. That is, it's already written for you. Sometimes, though, you need an array to pass to a framework method and you might as well have your method return it as opposed to returning a list or ienumerable and having to do the conversion each time.
tvanfosson
He didn't state that a list would be preferable, he stated "Returning arrays from method is not a wise thing" which doesn't make sense. There is nothing wrong with returning arrays.
Bob
@Bob it doesn't make sense to return a list of variables when you really want to return a list of values. An array is a list of variables.Read the details on http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx
Hasan Khan
+4  A: 

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();
    }
}
tvanfosson
I like to give the gc a workout! - just kidding - this is a very good point. Thanks.
Awesome solution!