0%

[Linq]動態組合Linq條件

以前寫Linq的時候常常碰到一個問題,就是判斷一個條件是否達成來決定Linq的Where條件該如何組合,
例如:

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
void Main()
{
bool Flag = true;
List<DealDataForGov> SourceData = new List<DealDataForGov>
{
new DealDataForGov
{
Address = "台北市xxxx",
HouseKind = "a1",
Year = 2015
},
new DealDataForGov
{
Address = "高雄市xxxx",
HouseKind = "a1",
Year = 2016
},
new DealDataForGov
{
Address = "台中市xxxx",
HouseKind = "c1",
Year = 2014
}
}

if (Flag)
{
SourceData.Where((x) => x.HouseKind == "a1");
}
else
{
//因為某個條件,新增新的搜尋條件
SourceData.Where((x) => x.HouseKind =="a1" && x.Year >= 2015 );
}
}

public class DealDataForGov
{
public string Address { get; set; }
public string HouseKind { get; set; }
public int Year {get;set;}
}

條件少還算好寫,一旦條件落落長的時候就會貼的到處都是,不僅彈性降低也讓維護增加困難度,還好在黑大那邊看到LINQKIT這個好東西黑暗執行緒-組裝動態LINQ條件的利器-LINQKit

以下簡短介紹一下這個LINQKit的套件,有了他之後感覺Code都活過來了XD
範例:

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
void Main()
{
List<TargetModel> SourceData = new List<TargetModel>
{
new TargetModel
{
Address = "台北市xxxx",
HouseKind = "a1",
Year = 2015
},
new TargetModel
{
Address = "高雄市xxxx",
HouseKind = "a1",
Year = 2016
},
new TargetModel
{
Address = "台中市xxxx",
HouseKind = "c1",
Year = 2014
}
};

var expression = GetWhereExpression();

//SourceData.Where((x) => x.HouseKind == "a1");
var e1 = SourceData.Where(expression.Compile());
e1.Dump();

//SourceData.Where((x) => x.HouseKind =="a1" && x.Year > 2015 );
var e2 = SourceData.Where(expression.And(x => x.Year > 2015).Compile());
e2.Dump();

//SourceData.Where((x) => x.HouseKind =="a1" || x.Year >=2014 );
var e3 = SourceData.Where(expression.Or(x => x.Year >= 2014).Compile());
e3.Dump();
}

public Expression<Func<TargetModel, bool>> GetWhereExpression()
{
var pred = PredicateBuilder.True<TargetModel>();
pred = pred.And(x=> x.HouseKind =="a1");
return pred;
}

public class TargetModel
{
public string Address { get; set; }
public string HouseKind { get; set; }
public int Year {get;set;}
}


上面有三個範例分別是替代掉註解的寫法,如果有碰到很多條件會動態產生的結果,用LinqKit可以大幅度省掉很多Code以及維護上的複雜度。算是非常好用的小物,推薦給大家