Convert linq query to string array - C#
60,846
Solution 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();
}
}
Solution 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();
Solution 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();
Author by
Admin
Updated on September 05, 2020Comments
-
Admin over 3 years
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