Creating dynamic Linq Queries - how to?

Last post 05-16-2008 6:42 PM by ShadowOfTheBeast. 4 replies.

Sort Posts:

  • Creating dynamic Linq Queries - how to?

    03-26-2008, 8:54 PM
    • Loading...
    • tsanet
    • Joined on 04-21-2006, 11:49 PM
    • Posts 56

    Hi gang,

    The article found here does a good job of describing the problem - dynamically adding where parameters to Linq queries, based on some text field.

    I managed to work around this with the following queries, but have since added an additional filtering field, which would make the most sense to add dynamically, instead of rewriting each query:

     

      
    1                IEnumerable dataImport = from ds in matches
    2                                                       orderby ds.FileUrl ascending
    3                                                       where ds.CampaignID == Convert.ToInt32(Session["CampaignID"].ToString())
    4                                                       select ds;
    5    
    6    
    7                // get TLP, CLP, or PLP
    8                if (DDPageType.SelectedValue != "ALL" & DDPageType.SelectedValue != "UNDEFINED")
    9                {
    10                   dataImport = from ds in db.tbl_DataImportMasterLists
    11                                orderby ds.FileUrl ascending
    12                                where ds.CampaignID == Convert.ToInt32(Session["CampaignID"].ToString())
    13                                && ds.PageType.ToUpper() == DDPageType.SelectedValue
    14                                select ds;
    15               }
    16   
    17               if (DDPageType.SelectedValue == "UNDEFINED")
    18               {
    19                   dataImport = from ds in db.tbl_DataImportMasterLists
    20                                orderby ds.FileUrl ascending
    21                                where ds.CampaignID == Convert.ToInt32(Session["CampaignID"].ToString())
    22                                && (ds.PageType.ToUpper() != "TLP" 
    23                                && ds.PageType.ToUpper() != "CLP" 
    24                                && ds.PageType.ToUpper() != "PLP")
    25                                select ds;
    26               }
    27   
    28               //
    29               // Retrieving data from DataImportMasterList
    30               //
    31               foreach (tbl_DataImportMasterList ds in dataImport)
    32               {
    33                   // build a page object
    34                   pageObject.FileUrl = ds.FileUrl;
    35                   pageObject.FileUrlDisplay = DisplayFileUrl(ds.FileUrl, ds.PageType);    // send page type for hover text
    36                   pageObject.TrackUrl = ds.TrackUrl;
    37                   .
    38                   .
    39                   .
    40                   // add it to an ArrayList
    41                   arrUlrList.Add(pageObject);
    42   
    43               }//foreach
    

     

    Basically I use IEnumerable to create a data object I can loop through for results.  The appropriate query is selected based on some on-page criteria (easy to see).  

    Now, I want to add a "CONTAINS" filter, based on a new text field on my form:

    1                IQueryable matches = db.tbl_DataImportMasterChanges;
    2                if (TxtStringSearch.Text.Length > 0)
    3                {
    4                    matches = matches.Where(row => row.Title.ToLower().Contains(TxtStringSearch.Text.ToLower().Trim()));
    5                }
    

     

    However, in line 1, at db, I get the following error:

    Cannot implicitly convert type 'System.Data.Linq.Table<tbl_DataImportMasterChange>' to 'System.Linq.IQueryable<tbl_DataImportMasterList>'  

    DataClassesDataContext db is an instance of my Linq-generated DataClasses.dbml.

     
    So given this, the question is, how to dynamically create a linq query with (not only CONTAINS), but ORDER BY, etc, and be able to iterate through the results?

     

    Thanks.
     

    --
    Some sig about something
    Filed under:
  • Re: Creating dynamic Linq Queries - how to?

    03-26-2008, 11:43 PM
    Answer
  • Re: Creating dynamic Linq Queries - how to?

    03-31-2008, 2:35 AM
    Answer

    Hi tsanet,

    To: So given this, the question is, how to dynamically create a linq query with (not only CONTAINS), but ORDER BY, etc, and be able to iterate through the results?

    Based on your requirements, you can use ToList method on your results which can persist your data into memory. In this case, you can use the data later and of course can iterate on the results. Here's a sample codes for you. Hope this helps you!

     

    List
    <Tag> tags = (from u in tagTx.Tags

    select u).ToList();

     

    Thanks.

    Sincerely,
    JanIvan Qian

    Please remember to click “Mark as Answer” on the post that helps you. This can be beneficial to other community members reading the thread.
  • Re: Creating dynamic Linq Queries - how to?

    04-02-2008, 6:02 PM
    • Loading...
    • tsanet
    • Joined on 04-21-2006, 11:49 PM
    • Posts 56

     Thanks PureWeen,

    I had actually stumbled across that site before, and glad I took a second look.

    I added Dynamic.cs to my project, and voila, works great!

     
    Below is the code, for those of you who may need it:

     

    1                StringBuilder sbCondition = new StringBuilder();
    2 3 sbCondition.Append("CampaignID == " + Convert.ToInt32(Session["CampaignID"].ToString()));
    4 // get TLP, CLP, or PLP 5 if (DDPageType.SelectedValue != "ALL" & DDPageType.SelectedValue != "UNDEFINED")
    6 {
    7 sbCondition.Append("&& PageType.ToUpper() == \"" + DDPageType.SelectedValue + "\"");
    8 }
    9 10 // no page definition 11 if (DDPageType.SelectedValue == "UNDEFINED")
    12 {
    13 sbCondition.Append("&& PageType.ToUpper() <> \"Page1\"");
    14 sbCondition.Append("&& PageType.ToUpper() <> \"Page2\"");
    15 sbCondition.Append("&& PageType.ToUpper() <> \"Page3\"");
    16 }
    17 18 // text search 19 if (TxtStringSearch.Text.Trim().Length > 0)
    20 {
    21 sbCondition.Append(" && " + DDSearchText.SelectedValue + ".Contains(\"" + TxtStringSearch.Text + "\")");
    22 }
    23 24 // build query 25 IEnumerable dataImport = from ds in db.tbl_MainCreatives
    26 .Where(sbCondition.ToString())
    27 .OrderBy(order)
    28 select ds;
    29 30 31 32 //
    33 // Retrieving data from DataImportMasterList
    34 //
    35 foreach (tbl_MainCreative ds in dataImport)
    36 { ... }
     

     
    --
    Some sig about something
  • Re: Creating dynamic Linq Queries - how to?

    05-16-2008, 6:42 PM

    Hi

    I am trying to do something Idetical as you but i am Querying a DataTable can you please help?

    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
Page 1 of 1 (5 items)