LinQ: Dynamic Query Where Clause + DataTable linq query

Last post 05-28-2008 12:09 PM by jchandra. 3 replies.

Sort Posts:

  • LinQ: Dynamic Query Where Clause + DataTable linq query

    05-16-2008, 6:11 PM

    Hi All,

    I am wondering if you could help me with this...I am quire new to linq and i am trying to construct a dynamic where clause

    for my linq query now i have been looking all over the web for examples but i cant find anything that seem to work for me...

    here is my query and i want my where clause to be composed of the following dynamic string returned by the method

    CreateFilter():

    this method builds up my query based on whether a user selected a series of drop down boxes and input data into text boxes or not .i.e it it does an AND or OR depending on what is selected or not selected

    I have the btnViewReport_Click(object sender, EventArgs e) Method which executes the query and puts the result in my gridview please find both methods below

    while the CreateFilter Method should build up the where clause but i cant get it to work, I read about using the Lambda expression but i dont know how to do this after looking at so many articles on the web they all seem to be in VB.Net and/or complicated predicates on how to do this which i still tried to no avail, please help!! i have marked out the problem area

    //see my Where Clause

    TestData = createFilter();

    /****************************************************************************************************

    Get All Data stored in the Cache which is the whole ResultSet returned By uspSearchPositionManager

    all 10512 rows and 103 columns into a DataTable "dt" via DataSet "ds"

    ****************************************************************************************************/

    dt = dsCache.Tables[0];

    /*LINQ query Expression: This Linq query object returns a filtered resultset data From the dataTable "dt"

    * Based on User input and selection Criteria on the webPage

    */

    /****************************************************************************************/

    string[] words = createFilter().Split(new string[] { "\r\n" }, StringSplitOptions.None);

    var queryWhere = dt.AsEnumerable();

    foreach (string word in words)

    {

    String thisWord = word;

    queryWhere = queryWhere.Where(Func<string>(word)(word.Contains(thisWord))); //this did not work!!!!! 6hours trying!!

    }

    /****************************************************************************************/

    IEnumerable<DataRow> query =

    from c in dt.AsEnumerable()

    //******************Different where clauses i was tring to use to make it work!!******************************************/

    //where c = createFilter()

    //where c.Field<string>("SecurityCode") == createFilter()

    //where c.Field<string>("SecurityCode") == createFilter()

    where c = createFilter().Split("\r\n")

    /****************************************************************************************/

    where c = createFilter() ///This Does not work!!!!!!!!!!!!!!!!!!!!

    select c;

    //see my Where Clause to know the format in the immediate window

    TestData = createFilter();

    /*Create a new DataTable "dtFormat" which then holds the filtered data returned by the LINQ query

    * formated into a DataTable to holding prior whihc is then bound to the gridview to return the

    * filtered data

    */

    dtFormat = new DataTable();

    if (dtFormat.Rows.Count != 0)
    {
    dtFormat = query.CopyToDataTable<DataRow>();
    }
    dataKeys =
    new string[1] { "SecurityCode" };

    gvPositionManager.DataKeyNames = dataKeys;

    gvPositionManager.DataSource = dtFormat;

    gvPositionManager.DataBind();

    //if Gridview has no rows then display the message

    if (gvPositionManager.Rows.Count == 0)

    {

    lblOutput.Visible =
    true;lblOutput.Text = "there are no records returned for the search criteria";

    }

    }

    /// <summary>

    /// This Method builds the where Clause the LINQ Query

    /// based on User selected criteria

    /// </summary>

    /// <returns></returns>

    private string createFilter()

    {

    StringBuilder filter = new StringBuilder();

    string ValueDate = msddlValueDate.List.SelectedValue;

    if (!ValueDate.Equals("-- Select All --"))

    {

    //filter.Append("ValueDate == msddlValueDate.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "ValueDate" + ") == msddlValueDate.List.SelectedItem.ToString() && \r\n ");

    //filter.Append(c.Field<string>(" + ValueDate + ") == msddlValueDate.List.SelectedItem.ToString() && \r\n ");

    }

    if (msddlSecurity.Text.Equals(""))

    {

    // filter.Append("SecurityCode == @SecurityCode && \r\n ");

    filter.Append("c.Field<string>(" + "SecurityCode" + ") == msddlSecurity.Text && \r\n ");

    }

    string Currency = msddlCurrency.List.SelectedValue;

    if (!Currency.Equals("-- Select All --"))

    {

    //filter.Append("Currency == msddlCurrency.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>("+ "Currency" + ") == msddlCurrency.List.SelectedItem.ToString() && \r\n ");

    }

    string Product = msddlProduct.List.SelectedValue;

    if (!Product.Equals("-- Select All --"))

    {

    //filter.Append("Product == msddlProduct.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "Product" + ") == msddlProduct.List.SelectedItem.ToString() && \r\n ");

    }

    string CountryIssue = msddlCountry.List.SelectedValue;

    if (!CountryIssue.Equals("-- Select All --"))

    {

    //filter.Append("CountryIssue == msddlCountry.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "CountryIssue" + ") == msddlCountryIssue.List.SelectedItem.ToString() && \r\n ");

    }

    if (txtValueFrom.Text.Equals(""))

    {

    //filter.Append("txtValueFrom == txtValueFrom.Text && \r\n ");

    filter.Append("c.Field<string>(" + "SettledValue" +") == txtValueFrom.Text && \r\n ");

    }

    if (txtValueTo.Text.Equals(""))

    {

    //filter.Append("txtValueTo == txtValueTo.Text && \r\n ");

    filter.Append("c.Field<string>(" + "SettledValue" + ") == txtValueTo.Text && \r\n ");

    }

    string Location = msddlLocation.List.SelectedValue;

    if (!Location.Equals("-- Select All --"))

    {

    //filter.Append("Location == msddlLocation.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "Location" + ") == msddlLocation.List.SelectedItem.ToString() && \r\n ");

    }

    /********* Not included as there seems to be no column for this value**********

    string LongShort = msddlLongShort.List.SelectedValue;

    if (!LongShort.Equals("-- Select All --"))

    {

    //filter.Append("LongShort == msddlLongShort.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "LongShort" + ") == msddlLongShort.List.SelectedItem.ToString() && \r\n ");

    }

    //*********************************************************************************/

    string Tag = msddlTag.List.SelectedValue;

    if (!Tag.Equals("-- Select All --"))

    {

    //filter.Append("Tag == msddlTag.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "Tag" + ") == msddlTag.List.SelectedItem.ToString() && \r\n ");

    }

    /* */ return filter.ToString();

    }

    This above all: to thine own self be true.

    William shakespeare, Hamlet
  • Re: LinQ: Dynamic Query Where Clause + DataTable linq query

    05-17-2008, 4:21 AM
    Answer
    • Loading...
    • jchandra
    • Joined on 05-15-2008, 5:36 AM
    • Jakarta, Indonesia
    • Posts 197

     Here is something to get you started...

     

    1            table = new DataTable("People");
    2            table.Columns.Add("Firstname", typeof (string));
    3            table.Columns.Add("Lastname", typeof (string));
    4            table.Rows.Add(new object[] {"John", "Doe"});
    5            table.Rows.Add(new object[] {"Jane", "Doe"});
    6            table.Rows.Add(new object[] {"Donald", "Duck"});
    7            table.Rows.Add(new object[] {"Jumping", "Jack"});
    8    
    9            bool filterOnFirstName = true;
    10           bool filterOnLastName = false;
    11    
    12           var query = table.AsEnumerable();
    13   
    14           if (filterOnFirstName)
    15           {
    16               query = query.Where(r => ((string) r["Firstname"]).StartsWith("J"));
    17           }
    18   
    19           if (filterOnLastName)
    20           {
    21               query = query.Where(r => ((string) r["Lastname"]).StartsWith("J"));
    22           }
    23   
    24           var queryFinal = from q in query
    25                            select new {FullName = q.Field<string>("Firstname") + " " + q.Field<string>("Lastname")};
    26   
    27           GridView1.DataSource = queryFinal;
    28           GridView1.DataBind();

    Jimmy Chandra
    Blogging at Incoherent Rambling

    Mark this post as Answer if you think it helped you solve the problem.

  • Re: LinQ: Dynamic Query Where Clause + DataTable linq query

    05-23-2008, 5:53 AM

    Hmmm....so it seems like no one knows how to do this then?

    This above all: to thine own self be true.

    William shakespeare, Hamlet
  • Re: LinQ: Dynamic Query Where Clause + DataTable linq query

    05-28-2008, 12:09 PM
    • Loading...
    • jchandra
    • Joined on 05-15-2008, 5:36 AM
    • Jakarta, Indonesia
    • Posts 197
    ShadowOfTheBeast:

    Hmmm....so it seems like no one knows how to do this then?

    Hmm... Do you still need help on this?  I thought the sample code that I gave before should be pretty clear and to the point to what you were asking.  Just need to customize it to fit your form.  Frankly I haven't find a way to combine that into one giant LINQ statement with all the conditions.  That's why I split them up into multiple LINQ queries which keep feeding into the next query and so on based on some conditions.

    Jimmy Chandra
    Blogging at Incoherent Rambling

    Mark this post as Answer if you think it helped you solve the problem.

Page 1 of 1 (4 items)