Best way to remove items from a collection

前端 未结 15 2050
天命终不由人
天命终不由人 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:44

    The best way to do it is by using linq.

    Example class:

     public class Product
        {
            public string Name { get; set; }
            public string Price { get; set; }      
        }
    

    Linq query:

    var subCollection = collection1.RemoveAll(w => collection2.Any(q => q.Name == w.Name));
    

    This query will remove all elements from collection1 if Name match any element Name from collection2

    Remember to use: using System.Linq;

提交回复
热议问题