2017-01-25 108 views
0

我已经以下类而不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

+0

的[根据病情从列表中删除项]可能的复制(HTT p://stackoverflow.com/questions/3279145/remove-item-from-list-based-on-condition) – pookie

+3

LINQ也会使用循环 - 这不是魔术。事实上,在这里使用LINQ(使用'GroupBy' /'Except'或你有什么)会导致一些效率低于循环自己的效率。如果列表在'(CategoryId,SectionId)'上排序,那么可以使用更有效的算法 - 但是排序当然本身会消耗时间。 –

回答

2
Products.RemoveAll(x => ProductsToRemove 
    .Any(r => x.CategoryId == r.CategoryId && x.SectionId == r.SectionId)); 
1

做同样可以在Any()组合使用Where()以达到所需的输出:

var deletion = Products 
    .Where(product=> ProductsToRemove 
        .Any(remove=> product.CategoryId == remove.CategoryId 
           && product.SectionId == remove.SectionId 
         ) 
     ); 
+0

输出应该包含3行产品ID 2,3,5。您的代码是否返回? –

+0

你有没有试过运行,它应该工作 –

+0

是的,这是只返回两个对象,那些将被删除,但我已经在ProductsToRemove –

0
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<Product> catsRemoved = Products.Where(x => x.CategoryId != 11 && x.CategoryId != 90).ToList(); 
+0

可以进一步检查部分ID在相同的where子句! – ramzagarland

+0

我不想在删除时对这些ID进行硬编码。它应该基于其他列表 –

+0

是的,然后ehsan和chadnt的答案是正确的 – ramzagarland