我有一個 LINQ 查詢,我在其中使用多個WHERE 陳述句過濾串列。
string[] filters = new string[]{"a","b","c","d"};
var filtered = from n in bigList where n != "a" where n != "b" where n != "c" where n != "c" select n;
如何使用過濾器陣列而不必撰寫多個 where 子句?
uj5u.com熱心網友回復:
認為這HashSet.Contains是一個O(1)操作,而Array.Contains是一個O(n)操作。
當然,如果陣列中只有 1-2 個(可能是 3 個)值,并且哈希演算法或字串數??據特別慢,那么 Array.Contains 可能會更快,但請考慮如果您只有 1-3 個元素,則只需使用單獨的區域變數而不是陣列,因為這樣會更快(因為它實際上是一個展開回圈)
HashSet<String> filterValueSet;
{
String[] filterValues = new String[]
{
"a", "b", "c", "d"
};
filterValueSet = new HashSet<String>( filterValues ); // Pass `StringComparer.OrdinalIgnoreCase` as the second argument for case-insensitive matching.
}
IReadOnlyList<String> filtered = bigList
.Where( v => !filterValueSet.Contains( v ) )
.ToList();
使用HashSet<String>like this 是過濾一組值的最快方法。
如果上面的代碼看起來很嚇人,可以簡化為:
HashSet<String> filterValueSet = new [] { "a", "b", "c", "d" }.ToHashSet();
IReadOnlyList<String> filtered = bigList
.Where( v => !filterValueSet.Contains( v ) )
.ToList();
uj5u.com熱心網友回復:
這就是答案,一個由另一個陣列過濾的陣列。
var filtered = bigList.Where(d => !filters.Contains(d));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510640.html
標籤:林克
