-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCollectionPredicateBuilder.cs
More file actions
88 lines (76 loc) · 2.81 KB
/
Copy pathCollectionPredicateBuilder.cs
File metadata and controls
88 lines (76 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ContainsOptimization
{
public static class CollectionPredicateBuilder
{
public static IQueryable<TSource> In<TSource, TCollection>(
this IQueryable<TSource> source,
IList<TCollection> collection,
Expression<Func<TSource, TCollection>> selector)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
if (selector == null)
{
throw new ArgumentNullException(nameof(selector));
}
var listType = typeof(List<TCollection>);
var addMethod = listType.GetMethod("Add");
var getItemMethod = listType.GetMethod("get_Item");
var containsMethod = listType.GetMethod("Contains");
// to-do: if index is > 2100 then we need to use constants
var initializers = collection
.Select((value, index) =>
Expression.ElementInit(
addMethod,
new[]
{
Expression.Call(
Expression.Constant(
collection,
listType),
getItemMethod,
new []
{
Expression.Constant(
index,
typeof(int))
})
}))
.ToList();
var bucket = 1;
while (initializers.Count > bucket)
{
bucket <<= 1;
}
bucket = bucket > 2098 ? 2098 : bucket;
if (initializers.Count > bucket)
{
throw new InvalidOperationException("In cannot be used with more than 2100 elements");
}
for (var index = initializers.Count; index < bucket; index++)
{
initializers.Add(initializers[index - 1]);
}
return source.Where(
Expression.Lambda<Func<TSource, bool>>(
Expression.Call(
Expression.ListInit(
Expression.New(
listType),
initializers),
containsMethod,
selector.Body),
selector.Parameters));
}
}
}