LINQ is it possible to add where clauses dynamically

前端 未结 5 1342
青春惊慌失措
青春惊慌失措 2021-01-05 02:36

I want to search my db with different keys. According to the input, there may be 1 key to 10 keys. Is there a way to add OR/AND clauses to my Linq query dynamically?

5条回答
  •  花落未央
    2021-01-05 03:23

    I wanted to provide an example of how @mellamokb's answer worked for my scenario to possibly help out anyone needing a fairly dynamic linq query.

    In my example I have simply made an extension of the datatable class so I can check if a row of data exists as it stands in the database so no SQL primary key exceptions are thrown.

    /// 
    /// 
    /// 
    /// 
    /// Columns to check in affected table.
    /// Values to check in affected column.
    /// 
    public static bool TableContains(this DataTable DT, string[] ColumnNames, object[] ItemtoChecks)
    {
      var result = from row in DT.AsEnumerable()
                   where ColumnNames.All(
                   r => row.Field(r).ToString() == Convert.ToString(
                     ItemtoChecks[ColumnNames.ToList()
                     .FindIndex(p => p.Equals(r, StringComparison.OrdinalIgnoreCase))]))
                   select row;                   
      return (result.Count() > 0);
    }
    
    
    

    This method allows you to add as many column names as you require to a string[] along with the corresponding values to check in a separate object[]. The query checks against the datatable and if it finds a match the method returns true and if not it returns false.

    提交回复
    热议问题