将 linq 查询转换为字符串数组 - C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1378801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:50:42  来源:igfitidea点击:

Convert linq query to string array - C#

c#linqarraysstringcasting

提问by

What is the most efficient way of converting a single column linq query to a string array?

将单列 linq 查询转换为字符串数组的最有效方法是什么?

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

注意 - x.Word 是一个字符串

采纳答案by tvanfosson

I prefer the lambda style, and you really ought to be disposing your data context.

我更喜欢 lambda 风格,你真的应该处理你的数据上下文。

private string[] WordList()
{
    using (DataContext db = new DataContext())
    {
       return db.Words.Select( x => x.Word ).OrderBy( x => x ).ToArray();
    }
}

回答by Robban

if you type it in Lambda syntax instead you can do it a bit easier with the ToArray method:

如果您改用 Lambda 语法键入它,您可以使用 ToArray 方法更轻松地完成它:

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

回答by Daren Thomas

How about:

怎么样:

return list.ToArray();

This is presuming that x.Wordis actually a string.

这是假设它x.Word实际上是一个字符串。

Otherwise you could try:

否则你可以尝试:

return list.Select(x => x.ToString()).ToArray();