[英]Filtering a collection of items from contents of another collection
這曾經為我工作,然后失敗了。 我想只返回包含所有過濾器的項目,而不是至少一個現在正在執行的過濾器。 這里有什么不對?
private IQueryable<IndexItem> FilteredIndex (IQueryable<IndexItem> index, IEnumerable<string> filters)
{
var filteredIndex= from f in filters.AsQueryable()
where f.Length>0
from i in index
where i.FilterNames.Contains(f)
select i;
return filteredIndex;
}
直接前進。 對於索引檢查中的給定項目,對於給定項目包含過濾器的所有過濾器都是如此。 這樣只需從索引中選擇所有項目,即給定條件為真。
index.Where(item =>
filters.All(filter => item.FilterNames.Contains(filter)))
我不確定是否需要檢查長度大於零,堅固它很容易集成。
index.Where(item =>
filters.All(filter =>
(filter.Length > 0 ) || (item.FilterNames.Contains(filter))))
它適用於LINQ to Objects,我猜它會做你想要的,但我不確定它是否適用於LINQ to SQL。
怎么樣的:
foreach(string s in filters) {
if(s.Length == 0) continue;
string tmp = s; // because of "capture" problem
index = index.Where(i => i.FilterNames.Contains(tmp));
}
return index;
這適用於一系列Where
子句,涵蓋所有過濾器 - 基本上是AND
。
扭轉局面。 你想要的是索引中的那些項目,其中FilterNames中的每個項目都在過濾器中有相應的條目。 我不確定它的表現如何,但計數比較應該如此。 就像是:
private IQueryable<IndexItem> FilteredIndex(IQueryable<IndexItem> index, IEnumerable<string> filter)
{
var filteredIndex = from i in index
where (from s in i.FilterNames
where filter.Contains(s)
select s).Count() == i.FilterNames.Count
select i;
return filteredIndex;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.