我可以在C#中动态生成的LINQ表达? [英] Can I generate a linq expression dynamically in C#?

查看:651
本文介绍了我可以在C#中动态生成的LINQ表达?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前得到一块的LINQ,看起来像这样;

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

List<dynamic> childrenToBeRemoved = this.ItemsSource.Where(o => o.ParentID == "1234").ToList();

其中的ItemsSource是动态的一个ObservableCollection。

where ItemsSource is an ObservableCollection of dynamics.

这工作得很好,但我有问题是PARENTID是可以改变的属性。例如。它可能被命名为ParentPkey或ParentKey等。

This works fine, but the problem I've got is that the ParentID is a property that can vary. E.g. it could be named ParentPkey or ParentKey etc.

我可以创建在那里我可以指定我想在我的比较中使用的属性的表达式?

Can I create an expression where I can specify the property that I want to use in my comparison?

我已经使用动态LINQ尝试,但它并没有采用动态的收集工作,正常工作与波苏斯的集合。

I've tried using dynamic linq but it doesn't work using a collection of dynamics, works fine with a collection of pocos.

谢谢...

推荐答案

为什么要实现本身的动态? !你可以简单地做一个动态调用

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");
}

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 ...我相信你应该告诉我们更多关于您的实际问题 - 我看不出有任何目前需要实施某事 - !所以,我相信,你的要求是不明确的。

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!

这篇关于我可以在C#中动态生成的LINQ表达?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆