Best way to remove items from a collection

前端 未结 15 2027
天命终不由人
天命终不由人 2020-12-08 05:47

What is the best way to approach removing items from a collection in C#, once the item is known, but not it\'s index. This is one way to do it, but it seems inelegant at be

15条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 06:42

    Save your items first, than delete them.

    var itemsToDelete = Items.Where(x => !!!your condition!!!).ToArray();
    for (int i = 0; i < itemsToDelete.Length; ++i)
        Items.Remove(itemsToDelete[i]);
    

    You need to override GetHashCode() in your Item class.

提交回复
热议问题