从Linq编译的查询返回KeyValuePair

roy*_*e41 3 c# linq compiled-query keyvaluepair

我刚刚接触到Linq中的Compiled Queries,并且遇到了一些奇怪的行为.

此查询编译正常:

public static Func<DataContext, string, object> GetJourneyByUrl =
    CompiledQuery.Compile<DataContext, string, object>((DataContext dc, string urlSlug) =>
        from j in dc.Journeys
        where !j.Deleted
        where j.URLSlug.Equals(urlSlug)
        select new KeyValuePair<string, int>(j.URLSlug, j.JourneyId)
    );
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将返回类型从对象更改为KeyValuePair时,如下所示:

public static Func<DataContext, string, KeyValuePair<string, int>> GetJourneyByUrl =
    CompiledQuery.Compile<DataContext, string, KeyValuePair<string, int>>((DataContext dc, string urlSlug) =>
        from j in dc.Journeys
        where !j.Deleted
        where j.URLSlug.Equals(urlSlug)
        select new KeyValuePair<string, int>(j.URLSlug, j.JourneyId)
    );
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

CS1662:无法将lambda表达式转换为委托类型'System.Func <DataContext,string,System.Collections.Generic.KeyValuePair <string,int >>',因为块中的某些返回类型不能隐式转换为委托返回类型

如何KeyValuePair从编译的查询中返回单个?或者我完全以错误的方式解决这个问题?

Yaa*_*lis 6

编译后的查询将返回一组值,因此为了使其工作,请尝试将返回类型更改为IEnumerable<KeyValuePair<string, int>>- 您将返回一组值,而不仅仅是一个值.然后,您可能希望将已编译查询的函数名称更改为GetJourneysByUrl.

然后,要从结果集中获取单个值(由函数名称隐含GetJourneyByUrl),那么您应该添加一个函数来返回编译查询返回的第一个项目.

public static KeyValuePair<string, int> GetJourneyByUrl(DataContext dc, string urlSlug) {
  return GetJourneysByUrl(dc, urlSlug).First();
}
Run Code Online (Sandbox Code Playgroud)

您也可以将其设置为Func,如此msdn页面显示的与编译查询相关的内容.