【问题标题】:Linq return string arrayLinq 返回字符串数组
【发布时间】:2011-09-09 12:30:20
【问题描述】:
/// <summary>
/// Returns list of popular searches
/// </summary>
public static string[] getPopularSearches(int SectionID, int MaxToFetch)
{
    using (MainContext db = new MainContext())
    {
        return (from c in db.tblSearches where c.SectionID == SectionID && c.Featured select new[] { c.Term });
    }
}

我查看了其他问题,但它们似乎略有不同,我得到了错误:

Cannot implicitly convert type 'System.Linq.IQueryable<string[]>' to 'string[]'

我知道这可能很简单,有人可以指出这里有什么问题吗?

【问题讨论】:

  • 是否有特殊原因需要返回数组?在大多数情况下,IEnumerable 会更可取,除非调用代码特别需要一个数组(不太可能)

标签: c# asp.net arrays string linq


【解决方案1】:

当然 - 您正试图从一个声明为返回 string[] 的方法返回,但您返回的是一个 查询 - 它本身并不是一个字符串。将查询转换为数组的最简单方法是调用ToArray 扩展方法。

但是,由于您已经为查询中的每个元素选择一个字符串数组,这实际上会返回string[][]。我怀疑你真的想为每个查询元素选择一个字符串,然后将整个东西转换成一个数组,即这样的代码:

public static string[] GetPopularSearches(int sectionID, int maxToFetch)
{
    using (MainContext db = new MainContext())
    {
        var query = from c in db.tblSearches
                    where c.SectionID == sectionID && c.Featured
                    select c.Term;
        return query.Take(maxToFetch)
                    .ToArray();
    }
}

请注意:

  • 我已重命名方法和参数以匹配 .NET 命名约定
  • 我添加了对Take 的调用,以便使用maxToFetch 参数

【讨论】:

    【解决方案2】:

    您正试图返回一个未实现的查询。只有在枚举查询时才会评估查询。幸运的是,ToArray 方法消除了枚举和存储的痛苦。只需将其添加到查询的末尾即可解决所有问题。

    return (
        from c in db.tblSearches 
        where c.SectionID == SectionID && c.Featured 
        select new[] { c.Term }
    ).ToArray();
    

    编辑

    也许更详细地看:

    return (
        from c in db.tblSearches 
        where c.SectionID == SectionID && c.Featured 
        select new[] { c.Term }
    ).SelectMany(x => x).ToArray();
    

    扁平化查询结果,甚至(减少冗余):

    return (
        from c in db.tblSearches 
        where c.SectionID == SectionID && c.Featured 
        select c.Term
    ).ToArray();
    

    【讨论】:

    • 如果我想要两个字段,而不仅仅是 c.Term,那会是什么样子?
    • @AlanFisher 你可以选择一个匿名对象:...select new{c.Term,c.SectionID}
    【解决方案3】:

    在 return 语句的末尾添加 .ToArray()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多