无需循环即可有效删除数据

时间:2017-01-25 20:14:44

标签: c# linq

我有以下课程

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,  }
    };

我想从Products实例中删除任何内容,其中CategoryId和SectionId与ProductsToRemove集合中的内容匹配。我知道如何遍历Products集合并删除匹配的记录,但我想知道是否有办法使用Linq做同样的事情

5 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您可以Where()组合使用Any()来获得所需的输出:

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

答案 2 :(得分: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();

答案 3 :(得分:0)

答案 4 :(得分:0)

对于那些不介意更改数据类型的人。

如果不允许键在您的集合中发生碰撞,则只能使用普通的Dictionary。或实施Equals并使用HashSet(请注意,HashSet是一个集合,而不是列表)

如果按键可能发生碰撞,您可以使用列表字典进行操作。

这是我的意思的一个例子。

Dictionary<string, List<Product>> Products = default;
List<Product> l = default.GetOrDefault(p.id1+"<|>"+p.id2); //LinQ extension on map
l.Clear();

当然,您总是可以将其包装在一个类中以将其伪装成一个列表,可能其中还包含一个实际的列表以保留顺序。