Idan
Idan

Reputation: 951

Create dynamically linq query

I have an EventLogEntry object:

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. 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. 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.

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)

Is there a way to do that?

Upvotes: 0

Views: 191

Answers (1)

McGarnagle
McGarnagle

Reputation: 102733

Why not use the Linq Contains with a list/array?

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:

// 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)
);

Upvotes: 1

Related Questions