Linq to Entitiesを使用しており、 using System.Linq.Dynamic;
を使用するstmtをusing System.Linq.Dynamic;
私の目標は、 whereClause
変数をemailListクエリにwhereClause
です(スクリーンショットを参照)。
何かご意見は?
++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++
@Michaelの提案を使用した後、私はそれを次のように動作させました:
HTML(フィールド値を「Value」属性に配置したことに注意してください):
<asp:CheckBoxList ID="_checkboxGroups" runat="Server">
<asp:ListItem Text="Sid Dickens Lovers" Value="SidDickens_TF" Selected="False" />
<asp:ListItem Text="Rosamond Lover" Value="Rosamond_TF" Selected="false" />
<asp:ListItem Text="Wine and Cheese Lovers" Value="WineAndCheese_TF" Selected="false" />
<asp:ListItem Text="Good Clients" Value="IntDesign_TF" Selected="false" />
<asp:ListItem Text="Vendors" Value="Vendor_TF" Selected="false" />
</asp:CheckBoxList>
コードビハインド:
// determine # of items in asp:CheckBoxList
var groupCount = _checkboxGroups.Items.Count;
var conditions = new List<string>();
for (int i = 0; i < groupCount; i++)
{
if (_checkboxGroups.Items[i].Selected)
{
conditions.Add(_checkboxGroups.Items[i].Value.ToString() + " == true");
}
}
string whereClause = string.Join(" OR ", conditions.ToArray());
ElanEntities3 db = new ElanEntities3();
var emailList = (from c in db.vEmailListViewforSendings
orderby c.Email
select c).AsQueryable();
emailList = emailList.Where(whereClause);
_listViewClients.DataSource = emailList;
System.Linq.Dynamic http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspxを使用している
var email = from c in db.MailListViewForSendings
order by c.ID
select c;
// then you chain the Linq;
email = email.Where("CategoryID=3");
パラメータを使用するには:
var email = from c in db.MailListViewForSendings
order by c.ID
select c;
// then you chain the Linq;
email = email.Where("CategoryID=@0", 3);
更新
StringBuilderを使用せず、代わりにList<string>
使用してから、それをstring.Joinで連結します。
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
var conditions = new List<string>();
conditions.Add("Lastname = 'Lennon'");
conditions.Add("Firstname = 'John'");
conditions.Add("Age = 40");
Console.WriteLine(string.Join(" OR ", conditions.ToArray() ));
}
}
出力:
Lastname = 'Lennon' OR Firstname = 'John' OR Age = 40
ライブテスト: http : //ideone.com/EFhnA
パラメータに一致するオブジェクトをIQueryable.Where(predicate)に渡す必要があります
したがって、 whereClause
はこのタイプのオブジェクトである必要があります。
Expression<Func<TSource, bool>>
AND演算ではなくwhere句のOR演算を行うため、大きなwhere句を1つ作成する必要があります。
データオブジェクトのタイプがOBJであり、ブールプロパティP0およびP1があるとします。
bool filterP0 = _checkboxGroups[0].Selected;
bool filterP1 = _checkboxGroups[1].Selected;
Expression<Func<OBJ, bool>> predicate = o =>
(
( !filterP0 && !filterP1 )
||
( filterP0 && o.P0 )
||
( filterP1 && o.P1 )
);
var emailList =
db.vEmailListViewForSendings
.Where( predicate )
.OrderBy( o => o.ID );
それはとにかく要点です。
または、実際に述語を動的に作成する必要がある場合は、 Joe AlbahariのPredicate Builderを使用できます。