[英]VB.Net how to use .FindAll in a List(of ) object?
我試過使用.Find()方法並且成功了。 但是我無法理解如何使用FindAll來接收匹配“靈活”關鍵字的所有項目(在我的情況下,這個關鍵字稱為ClassGuid)。
Public Class clsFindConnection
Private Delegate Function ConMatchDelegate(ByVal con As PropertyConnection, ByVal ClassGuid As String) As Boolean
Public Function GetPropertyConnectionsByGuid(ByVal ClassGuid As String, ByVal LBaseConnections As List(Of PropertyConnection)) As List(Of PropertyConnection)
Dim Res As List(Of PropertyConnection)
Dim dl As New ConMatchDelegate(AddressOf ConnectionFromMatch)
Res = LBaseConnections.FindAll(dl)'<-- ERROR. Can not work because delegate is only using a single item.
Return Res
End Function
Friend Function ConnectionFromMatch(ByVal con As PropertyConnection, ByVal ClassGuid As String) As Boolean
If con.PaintPluginFrom Is Nothing Then Return False
If con.PaintPluginFrom.Plugin Is Nothing Then Return False
If con.PaintPluginFrom.Plugin.Guid = ClassGuid Then Return True
Return False
End Function
End Class
怎么用這個?
使用lambda表達式傳遞第二個參數:
Res = LBaseConnections.FindAll(Function(con) ConnectionFromMatch(con, ClassGuid))
編輯回答你的評論:
FindAll
采用Predicate(Of T)
(在你的情況下為Predicate(Of PropertyConnection)
),因此你不能將ConMatchDelegate
傳遞給它,因為簽名不兼容。 所以我使用匿名方法創建了一個Predicate(Of PropertyConnection)
。 這可能更容易理解:
Dim filter As Predicate(Of PropertyConnection) = Function(con) ConnectionFromMatch(con, ClassGuid)
Res = LBaseConnections.FindAll(filter)
對不起,我是C#家伙,但我希望我們可以在這里分享一個概念。
List類的FindAll方法采用謂詞 。 Predicate是一個專門的委托,它接受一個參數並返回一個布爾值。 因此,FindAll在內部對列表中的每個項進行迭代,哪個項滿足謂詞中定義的條件,將包含在結果中。
class Program
{
static void Main(string[] args)
{
List<PropertyConnection> lstConn = new List<PropertyConnection>(){
new PropertyConnection() { Id = 10},
new PropertyConnection() { Id = 20 },
new PropertyConnection() { Id = 30 } };
List<PropertyConnection> filtered = lstConn.FindAll(MyDelegate);
// so filtered contains just one item with Id = 30
}
private static bool MyDelegate(PropertyConnection con) // your own delegate
{
if (con.Id > 20)
return true;
else
return false;
}
}
public class PropertyConnection // sample class
{
public int Id;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.