Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Drawing.Drawing2D;
- using System.Windows.Forms.DataVisualization.Charting;
- using System.Linq.Expressions;
- namespace Test_2
- {
- public partial class Form1 : Form
- {
- private List<Expression<Func<Personnel, bool>>> personnelFilter = new List<Expression<Func<Personnel,bool>>>();
- public Form1()
- {
- InitializeComponent();
- AddFilter(a => a.FirstName == "Test");
- AddFilter(a => a.FirstName == "More");
- // Or adding something stupid like:
- AddFilter(a => a.Id == 1);
- }
- public void AddFilter(Expression<Func<Personnel, bool>> filter)
- {
- this.personnelFilter.Add(filter);
- }
- public static Expression<Func<T, bool>> Combine_Or<T>(Expression<Func<T, bool>> expr1,
- Expression<Func<T, bool>> expr2)
- {
- var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
- return Expression.Lambda<Func<T, bool>>
- (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
- }
- private Expression<Func<Personnel, bool>> JoinFilter()
- {
- var result = personnelFilter[0];
- for (int i = 1; i < personnelFilter.Count; i++)
- result = Combine_Or<Personnel>(result, personnelFilter[i]);
- return result;
- }
- private void button1_Click(object sender, EventArgs e)
- {
- List<Personnel> personnel = new List<Personnel> {
- new Personnel { Id=3, FirstName="walter" },
- new Personnel { Id=1, FirstName="More" },
- new Personnel { Id=1, FirstName="More" },
- new Personnel { Id=1, FirstName="john" },
- new Personnel { Id=2, FirstName="michael" },
- new Personnel { Id=2, FirstName="Test" },
- new Personnel { Id=1, FirstName="Raj" }
- };
- Func<Personnel, bool> filter = JoinFilter().Compile();
- var filtered = personnel.Where(filter);
- foreach (var item in filtered)
- System.Console.WriteLine(item.FirstName);
- /* Prints:
- More
- More
- john
- Test
- Raj
- */
- }
- }
- public class Personnel
- {
- public int Id { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public int OrganizationalUnitId { get; set; }
- public int RoleId { get; set; }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement