C# Linq where clause as a variable

后端 未结 5 734
后悔当初
后悔当初 2020-12-01 07:30

I am trying to make a LINQ statement where the where clause comes from a variable. For example:

string whereClause = address.zip == 23456;
var x = from somet         


        
相关标签:
5条回答
  • 2020-12-01 07:46

    Can try:

    var lstQ_Buffer = new List<Q_Buffer>();
    

    Get

    lstQ_Buffer = unitOfWork.Q_BufferRepository.Get().ToList();
    

    Then apply where

    if (lstQ_Buffer.Count > 0)
    {
        lstQ_Buffer = lstQ_Buffer.Where(q => q.fkProgramId == programId && q.fkYearId == yearId && q.fkSemesterId == semesterId && q.fkCourse_ModuleId == courseModuleId && q.fkSubject_SpecialtyId == subjectSpecialtyId && q.fkSubSpecialtyId == subSpecialtyId && q.fkTopicId == topicId && q.fkSubTopicId == subTopicId && q.fkDifficultyLevelId == diffucultyLevelId).ToList();
    }
    
    0 讨论(0)
  • 2020-12-01 07:50

    You need to assembly an Expression<Func<T, bool>> and pass it to the Where() extension method:

    Expression<Func<T, bool>> whereClause = a => a.zip == 23456;
    var x = frSomeList.Where(whereClause);
    

    EDIT: If you're using LINQ to Objects, remove the word Expression to create an ordinary delegate.

    0 讨论(0)
  • 2020-12-01 07:54

    As Richard has pointed out, the Dynamic Query Library can be used to build dynamic filter expressions. When using Linq-To-Objects make sure to convert your IEnumerable<T> to a IQueryable<T> first. Here is an (incomplete) example:

    using System.Linq.Dynamic;
    
    namespace System.Linq.Dynamic
    {
      public class Example
      {
       // Assuming some value is assigned to below field somewhere... 
       private IEnumerable<Address> m_Addresses;
    
       public void FilterByZipCode(string zipCode)
       {
          var x = m_Addresses.AsQueryable().Where("Zip == @0", zipCode);
          dowork(x);
       }
      }
    
      public class Address
      {  
         public String Zip { get; set; }
    
         // More Properties...  
      }
    }
    
    0 讨论(0)
  • 2020-12-01 08:02

    That's a built-in Feature of LINQ. Just use the Where extension method.

    See LINQ Query Syntax versus Method Syntax (C#) for more information.

    0 讨论(0)
  • 2020-12-01 08:10

    This:

    var query = from something in someList where whereClause;
    

    is shorthand for:

    var query = someList.Where(something => whereClause);
    

    Assuming someList is an IEnumerable<Address>, Where refers to the Enumerable.Where Extension Method. This method expects a Func<Address, bool> which you can define as follows:

    Func<Address, bool> whereClause = address => address.Zip == 23456;
    var query = someList.Where(whereClause);
    
    0 讨论(0)
提交回复
热议问题