Can I generate a linq expression dynamically in C#?

后端 未结 4 987
遥遥无期
遥遥无期 2021-01-22 08:40

I\'ve currently got a piece of Linq that looks something like this ;

List childrenToBeRemoved = this.ItemsSource.Where(o => o.ParentID == \"123         


        
相关标签:
4条回答
  • 2021-01-22 09:24

    Put you linq expression into a function, and pass in this property as a parameter.

    0 讨论(0)
  • 2021-01-22 09:28

    why make the implementation itself dynamic? you could simply do a dynamic invocation!

    IEnumerable<MyItem> result;
    if (condition1)
    {
        result = this.Items.Where(arg => arg.ProductId == "123");
    }
    else if (condition2)
    {
        result = this.Items.Where(arg => arg.ProductPK == "123");
    }
    

    or

    Func<Item, bool> predicate;
    if (condition1)
    {
        predicate = item => item.ProductId == "123";
    }
    else if (condition2)
    {
        predicate = item => item.ProductPK == "123";
    }
    var result = this.Items.Where(predicate);
    

    Sooo ... I believe you should tell us more about your actual problem - I do not see any current need to implement sth - so, I believe your requirement is ill-defined!

    0 讨论(0)
  • 2021-01-22 09:30

    If you know the type of your items, you can use reflection :

    PropertyInfo parentProp = itemType.GetProperty("ParentKey or whatever");
    List<dynamic> childrenToBeRemoved = this.ItemsSource.Where(o => Equals("1234", parentProp.GetValue(o, null))).ToList();
    
    0 讨论(0)
  • 2021-01-22 09:43

    it should not matter if query is dynamic linq or not

    Expression<Func<Entity, int>> predicate = x => x.Id == myvalue;
    from entity in _context.Entities.Where(predicate)
    select entity;
    

    Check out PredicateBuilder of LinkKit @ http://www.albahari.com/nutshell/linqkit.aspx there are enough examples there as well

    Responsibility of translation of an expression to corresponding sql lies with the linq provider, so make sure the provider you are using supports the relevant aspects

    0 讨论(0)
提交回复
热议问题