开发者

Does Dynamic Linq support BindingList<T>?

Question

I'm trying to use the Dynamic Linq Sample from Microsoft with BindingList<T> objects. But it looks like the Dynamic Linq will only work with IQueryable. What's the deal here, why doesn't BindingList<T> implement IQueryable. And is there a way around this?


Background Detail: I have many data sets that I need to dynamically filter at run time. Here is an example:

BindingList<MyObject> list = new BindingList<MyObject>();
MyObject selectedObj = list.FirstOrDefault(o => o.Name == "Master P")

// then later ...
MyObject selectedObj = list.FirstOrDefault(o => o.City == "Boston")

I am trying to make these queries dynamic, so the user can choose from all p开发者_如何学Pythonroperties of MyObject to use in the query.


There is an Extension method on BindingList; AsQueryable(). So you can use

list.AsQueryable();

But if you want to search on all criteria could you create a search that uses an instance of MyObject as the search criteria and then generated a result set based on the Criteria in the object using standard link.

For example:

public List<MyObject> Search(MyObject SearchCriteria)
    {
        BindingList<MyObject> list = new BindingList<MyObject>();
        list.Add(new MyObject("Test", "Boston"));
        list.Add(new MyObject("Test2", "Atlanta"));

        IEnumerable<MyObject> results = list.AsEnumerable();
        if (!String.IsNullOrEmpty(SearchCriteria.Name))
            results = results.Where(l => l.Name.Contains(SearchCriteria.Name));
        if (!String.IsNullOrEmpty(SearchCriteria.City))
            results = results.Where(l => l.City.Contains(SearchCriteria.City));
        return results.ToList();

    }

So in the following, Results1 will have 2 results and Results 2 will have only 1.

List<MyObject> results1 = Search(new MyObject("Test", ""));
List<MyObject> results2 = Search(new MyObject("Test", "Boston"));

I used a simple structure for MyObject as an example in this:

public class MyObject
{
    public MyObject(string name, string city)
    {
        this.Name = name;
        this.City = city;
    }
    public string Name { get; set; }
    public string City { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜