我已经以下类而不for循环
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public int SectionId { get; set; }
public string VendorName { get; set; }
}
public class ProductToRemove
{
public int CategoryId { get; set; }
public int SectionId { get; set; }
}
在主我有这两个类如下的列表有效去除数据。
List<Product> Products = new List<Product>()
{
new Product() { Id = 1, Name = "A", CategoryId = 11, SectionId = 6, VendorName = "ABC" },
new Product() { Id = 2, Name = "B", CategoryId = 21, SectionId = 6, VendorName = "ABC" },
new Product() { Id = 3, Name = "C", CategoryId = 13, SectionId = 8, VendorName = "ABC" },
new Product() { Id = 4, Name = "D", CategoryId = 90, SectionId = 6, VendorName = "ABC" },
new Product() { Id = 5, Name = "E", CategoryId = 25, SectionId = 9, VendorName = "ABC" },
};
List<ProductToRemove> ProductsToRemove = new List<ProductToRemove>()
{
new ProductToRemove() {CategoryId = 11, SectionId = 6, },
new ProductToRemove() {CategoryId = 90, SectionId = 6, }
};
我想从产品实例中删除任何其中CategoryId和SectionId与ProductsToRemove集合中的内容相同的任何实例。我知道如何通过产品收集循环和删除匹配的记录,但我想知道如果有一种方法使用LINQ
的[根据病情从列表中删除项]可能的复制(HTT p://stackoverflow.com/questions/3279145/remove-item-from-list-based-on-condition) – pookie
LINQ也会使用循环 - 这不是魔术。事实上,在这里使用LINQ(使用'GroupBy' /'Except'或你有什么)会导致一些效率低于循环自己的效率。如果列表在'(CategoryId,SectionId)'上排序,那么可以使用更有效的算法 - 但是排序当然本身会消耗时间。 –