简体   繁体   English

动态创建linq查询

[英]Create dynamically linq query

I have an EventLogEntry object: 我有一个EventLogEntry对象:

EventLog aLog = new EventLog("Application");
IEnumerable<EventLogEntry> logentry=aLog.Entries.Cast<EventLogEntry>();

Now I'm trying create a dynamical linq query on logentry by its InstanceId . 现在,我尝试通过InstanceIdlogentry上创建动态linq查询。 I can run this: 我可以运行:

int id=123;
IEnumerable<EventLogEntry> filteredByEventId = logentry.Where((x) => x.InstanceId == id);

but I'm trying to create linq terms at runtime. 但我试图在运行时创建linq术语。 Something like this: 像这样:

int id=123;
int id2=456;
IEnumerable<EventLogEntry> filteredByEventId = logentry.Where((x) => x.InstanceId == id || x.InstanceId == id2);

While I get that there is the "id2" too to add the the term at runtime. 虽然我知道在运行时也添加了“ id2”一词。

Update: my main goal is the user can ask for InstanceId range like 123, 456-789, 1000-1005 and i need to create the right query (dynamically) that will show him all event with the following InstanceId 123 and between 456-789 (and 1000-1005) 更新:我的主要目标是用户可以要求InstanceId范围,例如123、456-789、1000-1005,并且我需要创建正确的查询(动态地),该查询将向他显示以下InstanceId 123和456-789之间的所有事件(和1000-1005)

Is there a way to do that? 有没有办法做到这一点?

Why not use the Linq Contains with a list/array? 为什么不将Linq 包含与列表/数组一起使用?

var ids = new List<int>();
ids.Add(123);
ids.Add(456);
// etc...

IEnumerable<EventLogEntry> filteredByEventId = logentrey.Where((x) => ids.Contains(x.InstanceId));

Edit 编辑

To apply multiple ranges, you could use a collection of min/max tuples, and then use the Linq All method to filter by each range: 要应用多个范围,可以使用最小/最大元组的集合,然后使用Linq All方法按每个范围进行过滤:

// setup ranges
var ranges = new List<Tuple<int, int>>();
ranges.Add(new Tuple<int,int>(123,123));
ranges.Add(new Tuple<int,int>(456,789));
ranges.Add(new Tuple<int,int>(1000,1005));

// apply filter
var filteredByEventId = logentry.Where(x => 
    ranges.All(range => x >= range.Item1 && x <= range.Item2)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM