簡體   English   中英

C#LINQ在單次執行中從列表中刪除多個對象

[英]C# LINQ Remove multiple objects from a list in single execution

它似乎很相似,但我的問題卻完全不同。 我有一個列表,其中包含實現不同接口的對象。 我想刪除特定類型的對象,但是在傳遞了另一個標准之后。 下面給出了示例代碼。

 // remove the not required parameters 
foreach (EndPoint endPoint in endPoints)
{                 
    var maps = endPoint.EndPointParameters
        .Where(x => x is IEndPointParamMapCustom)
        .Cast<IEndPointParamMapCustom>()
        .Where(x => !x.IsActive)
        .ToList();

    foreach (var custom in maps)
    {
        endPoint.EndPointParameters.Remove(custom);
    }
}

我想刪除下面的foreach循環並刪除上面單個LINQ查詢中的對象。 可能嗎? 謝謝。

你可以使用RemoveRange函數endPoint.endPointParameters.RemoveRange(maps)

如果EndPointParametersList<T> (“從列表中刪除多個對象”),您可以嘗試RemoveAll而不是Linq

// Remove the not required parameters 
foreach (EndPoint endPoint in endPoints)
{ 
    // Remove all items from EndPointParameters that both
    //   1. Implement IEndPointParamMapCustom 
    //   2. Not IsActive 
    endPoint
      .EndPointParameters                
      .RemoveAll(item => (item as IEndPointParamMapCustom)?.IsActive == false);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM