简体   繁体   English

如何过滤通用对象列表

[英]How to filter a list of generic objects

I have find the code to implement a SortableBindingList that extends of BindingList and it theoretically let sort and filter a list of generic objects. 我已经找到实现BindingList扩展的SortableBindingList的代码,并且从理论上讲,它可以排序和过滤通用对象列表。 It works perfectly sorting the list but I can not get filtering. 它可以完美地对列表进行排序,但我无法过滤。

The filter code is as follows 过滤器代码如下

       Protected Sub UpdateFilter()
        _isSorted = False 'remove sort.
        Try
            'We filter on the entire collection
            Dim filtered = _originalData.AsQueryable()

            If Not String.IsNullOrEmpty(_filter) Then filtered = filtered.Where(_filter)

            Dim filteredResult = filtered.ToList()
            Items.Clear()

            If filteredResult IsNot Nothing AndAlso filteredResult.Count > 0 Then
                For Each tItem As T In filtered
                    Items.Add(tItem)
                Next
            End If
        Catch
            'Reset the list
            Items.Clear()
            For Each tItem As T In _originalData
                Items.Add(tItem)
            Next

            'Rethrow the error
            Throw
        Finally
            OnListChanged(New ListChangedEventArgs(ListChangedType.Reset, -1))
        End Try
    End Sub

The problem is that the following example receive like a filter a string in the clause where but the compile trhow an error since it wait a function I don't know how to resolve this 问题是以下示例在子句中像过滤器一样接收字符串,但是编译会出错,因为它等待一个函数,我不知道如何解决这个问题

Sorry if you do not understand well. 不好意思,不好意思。 I do not speak English well 我英语说得不好

You need to pass a predicate. 您需要传递一个谓词。 I hope this example will guide you. 我希望这个例子能指导您。

Private Function AddFilter(list As List(Of String), filter As Func(Of String, Integer, Boolean)) As List(Of String)
    Dim l As IEnumerable(Of String) = Nothing
    If Not IsNothing(filter) Then
        l = list.Where(filter)
    End If
    Return l.ToList
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim A As New List(Of String) From {"Mathew", "Mark", "Luke", "John"}
    Dim predicate As Func(Of String, Integer, Boolean) = Function(str, index) str.StartsWith("M")
    Dim FilteredList = AddFilter(A, predicate)
    For Each s As String In FilteredList
        Debug.Print(s)
    Next
End Sub

There is an answer in some post that recommend this. 在某些帖子中有一个建议这样做的答案。

You can use Dynamic Linq: 您可以使用动态Linq:

Dim filter As String = "property1>10 and property2 like 'anystring' or property3<=25". Dim筛选器为String =“ property1> 10,并且property2如'anystring'或property3 <= 25”。

Dim results = Elements.Where(filter). 昏暗的结果= Elements.Where(filter)。

But I don't know how to use dinamic linq 但是我不知道如何使用dinamic linq

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

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