Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从Linq编译查询返回KeyValuePair_C#_Linq_Compiled Query_Keyvaluepair - Fatal编程技术网

C# 从Linq编译查询返回KeyValuePair

C# 从Linq编译查询返回KeyValuePair,c#,linq,compiled-query,keyvaluepair,C#,Linq,Compiled Query,Keyvaluepair,我刚刚开始处理Linq中的编译查询,遇到了一些奇怪的行为 此查询可以很好地编译: public static Func<DataContext, string, object> GetJourneyByUrl = CompiledQuery.Compile<DataContext, string, object>((DataContext dc, string urlSlug) => from j in dc.Journeys

我刚刚开始处理Linq中的编译查询,遇到了一些奇怪的行为

此查询可以很好地编译:

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)
    );
public static Func GetJourneyByUrl=
CompiledQuery.Compile((DataContext dc,字符串URLSLAUG)=>
从华盛顿的j.旅行
哪里!j.被删除了
其中j.urlslag.Equals(urlslag)
选择新的KeyValuePair(j.urlslag,j.JourneyId)
);
但当我尝试将返回类型从object更改为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)
    );
public static Func GetJourneyByUrl=
CompiledQuery.Compile((DataContext dc,字符串URLSLAUG)=>
从华盛顿的j.旅行
哪里!j.被删除了
其中j.urlslag.Equals(urlslag)
选择新的KeyValuePair(j.urlslag,j.JourneyId)
);
我得到以下错误:

CS1662:无法将lambda表达式转换为委托类型 'System.Func' 因为块中的某些返回类型不是隐式的 可转换为委托返回类型


如何从已编译查询返回单个
KeyValuePair
?或者我的做法完全是错误的?

编译后的查询将返回一组值,因此为了使其正常工作,请尝试将返回类型更改为
IEnumerable
——您返回的是一组值,而不仅仅是一个值。然后,您可能希望将已编译查询的函数名更改为
GetJourneysByUrl

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

public static KeyValuePair<string, int> GetJourneyByUrl(DataContext dc, string urlSlug) {
  return GetJourneysByUrl(dc, urlSlug).First();
}
public static KeyValuePair GetJourneyByUrl(DataContext dc,字符串urlslaug){
返回GetJourneysByUrl(dc,urlslaug.First();
}

您还可以将其设置为
Func
,如图所示。

然后使用.First()或.Single(或类似方法)获取所需的值!我没有创建另一个包装器方法,而是将初始查询(在Func中)包装到(),然后使用first或default。谢谢