C# 从Linq编译查询返回KeyValuePair
我刚刚开始处理Linq中的编译查询,遇到了一些奇怪的行为 此查询可以很好地编译: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
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。谢谢