使用动态创建的LINQ过滤列表 [英] Filter list using a dynamically created LINQ

查看:65
本文介绍了使用动态创建的LINQ过滤列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows窗体网格,其中BindingList< myobj>已设置为数据源.现在,我想根据用户给定的条件过滤网格中的数据.该列表可以包含诸如ItemCode,Name,Price之类的列.如果用户说ItemCode ="aa"或Name ="bb",该如何动态创建LINQ并过滤网格.

I have a windows form grid that BindingList<myobj> has set as the datasource. Now I want to filter the data in the grid according to the given condition by the user. This list can have columns like ItemCode, Name, Price. If user says ItemCode="aa" or Name ="bb" how can I dynamically create the LINQ and filter the grid.

推荐答案

我假设您的用户将输入Name = aa或ItemCode = bb等格式.在这种情况下,您需要使用类似以下内容将条目分为两部分:-

I assume your user will enter Name=aa or ItemCode=bb etc in that format. In that case you would need to split the entry into it''s 2 parts using something like this:-

string[] searchArray = txtNameSearch.Text.Split(new char[] { '=' });



然后可以使用switch语句来调用采用Predicate<>的方法.作为参数,并在调用时传递lambda表达式,如下所示:-



you could then use a switch statement to call a method that takes a Predicate<> as a parameter and pass in a lambda expression when you call it, something like this:-

private void Filter(Predicate<myClass> filter)
       {
           List<myClass> filteredClassList = (from myclass in myClassList where filter(myclass) select myclass).ToList();
           dgMyClass.DataContext = filteredClassList;
       }





switch (searchArray[0])
           {
               case "Name":
                   Filter(myclass => myclass.Name.Contains(searchArray[1]) == true);
                   break;
               case "ItemCode":
                   Filter(myclass => myclass.ItemCode.Contains(searchArray[1]) == true);
                   break;
                   //etc
           }



我使用WPF表单和DataGrid对此进行了测试,但是对于WinForms项目,它是相同的,只是将DataContext更改为DataSource

希望对您有所帮助



I used a WPF form and DataGrid to test this but it would be the same for a WinForms project, just change DataContext to DataSource

Hope this helps


请参阅此链接

http://msdn.microsoft.com/en-us/vcsharp/aa336746 [ ^ ]
see this link

http://msdn.microsoft.com/en-us/vcsharp/aa336746[^]


这篇关于使用动态创建的LINQ过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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