我是 Linq 的初学者,现在很多内容都完全令人困惑。
我从 http://linqflickr.codeplex.com 下载并使用了 LinqFlickr 库。不过我认为这只是我对 Linq 缺乏了解。 LinqFlickr 项目上没有太多文档供我继续。
如果我运行以下代码,如果用户名字符串为空,它将正常运行并返回带有特定标签的照片。但如果其中有用户名,它应该根据特定用户来优化之前的结果,而不是给我一堆随机照片。
var photos = (from ph in context.Photos
where
ph.SearchMode == SearchMode.TagsOnly
&& ph.SearchText == tag
&& ph.PhotoSize == PhotoSize.Small
&& ph.Extras == (ExtrasOption.Owner_Name | ExtrasOption.Date_Taken)
select ph);
if (username != "")
{
string personId = (from people in context.Peoples
where
people.Username == username
select people.Id).First();
photos = photos.Where(q => q.NsId == personId) ;
}
photos = photos.Take(10);
我尝试使用一些调试工具,例如 LinqPad 和 MetaLinq,但无法解决该问题。
另外,我确信我的 Linq 查询可以在一个查询中进行,这会很棒,但请解释一下,以便 Linq 新手能够理解!
最佳答案
您的查询看起来不错。我的猜测是,这是 Athena 中的一个错误(或不直观的设计行为),其中额外的“链接”where
子句导致原始 where
子句被遗忘。
独立组装第二个查询(即一个大 where
子句中的所有约束)并检查这是否修复了问题。如果确实如此,则肯定是 API 中的错误。您可以使用 LINQKit 来解决此问题动态组装和扩展 where
子句的谓词。看起来可能是这样的:
// Original predicate without userId constraint
Expression<Func<Photo, bool>> predicate = ph =>
ph.SearchMode == SearchMode.TagsOnly
&& ph.SearchText == tag
&& ph.PhotoSize == PhotoSize.Small
&& ph.Extras == (ExtrasOption.Owner_Name | ExtrasOption.Date_Taken);
if (!string.IsNullOrEmpty(username))
{
// Build the userId constraint into the predicate.
var personId = (from people in context.Peoples
where people.Username == username
select people.Id).First();
// "And" combines the predicates
// "Expand" removes the use of invocation expressions, which
// some LINQ providers have problems with.
predicate = predicate.And(q => q.NsId == personId).Expand();
}
// Final result
var photos = context.Photos.Where(predicate).Take(10);
关于c# - Linq:添加额外的 'Where' 子句给出随机结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9484350/