簡體   English   中英

如何從列表中刪除 object 的實例?

[英]How to remove an instance of object from the list?

我想從列表中刪除 object 的實例。

我查閱了 Microsoft 文檔 ( https://learn.microsoft.com/en-us/do.net/api/system.collections.generic.list-1.remove?view.netcore-3.1 ) 來解決我的問題問題,這是我正在尋找的部分:

// This will remove part 1534 even though the PartName is different,
// because the Equals method only checks PartId for equality.
parts.Remove(new Part(){PartId=1534, PartName="cogs"});

我想輸入屬性名稱的值,並刪除具有相應名稱的實例。

Console.Write("Enter name: ");
Name = Console.ReadLine();
//even though it doesn't make much sense to me, I've tried a few things, the latest being...
triangles.Remove(new Triangle(Name, A = 0) { Name = Name, A = 0 });

你考慮過RemoveAll嗎?

public class Program
{
    static void Main(string[] args)
    {
        List<TestObject> myList = new List<TestObject>();
        myList.Add(new TestObject {ID=1, Name="Name"});

        myList.RemoveAll(x => x.ID == 1 && x.Name == "Name");
    }
}

//Just a dummy example class
public class TestObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

在調用RemoveAll之后,列表將為空(在此特定示例中)。
請注意,我還忽略了RemoveAll的返回值。 它返回一個表示已刪除項目數的int ,這可能會有所幫助。

暫無
暫無

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

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