简体   繁体   English

如何使用 linq 通过多个变量从列表中删除对象

[英]how to remove objects from list by multiple variables using linq

I want to remove objects from a list using linq, for example:我想使用 linq 从列表中删除对象,例如:

public class Item
{
    public string number;
    public string supplier;
    public string place;
}

Now i want to remove all of the items with the same number and supplier that appear more then once.现在我想删除所有出现多次的具有相同编号和供应商的项目。
Thanks谢谢

This would be slightly tedious to do in-place, but if you don't mind creating a new list, you can use LINQ.就地执行此操作会有些乏味,但如果您不介意创建新列表,则可以使用 LINQ。

The easiest way to specify your definition of item-equality is to project to an instance of an anonymous-type - the C# compiler adds a sensible equality-implementation on your behalf:指定项目相等定义的最简单方法是投影到匿名类型的实例 - C# 编译器代表您添加了一个合理的相等实现:

List<Item> items = ...

// If you mean remove any of the 'duplicates' arbitrarily. 
List<Item> filteredItems = items.GroupBy(item => new { item.number, item.supplier })
                                .Select(group => group.First())
                                .ToList();

// If you mean remove -all- of the items that have at least one 'duplicate'.
List<Item> filteredItems = items.GroupBy(item => new { item.number, item.supplier })
                                .Where(group => group.Count() == 1)
                                .Select(group => group.Single())
                                .ToList();

If my first guess was correct, you can also consider writing an IEqualityComparer<Item> and then using the Distinct operator:如果我的第一个猜测是正确的,您还可以考虑编写一个IEqualityComparer<Item>然后使用Distinct运算符:

IEqualityComparer<Item> equalityComparer = new NumberAndSupplierComparer();
List<Item> filteredItems = items.Distinct(equalityComparer).ToList();

Btw, it's not conventional for types to expose public fields (use properties) or for public members to have camel-case names (use pascal-case).顺便说一句,类型公开公共字段(使用属性)或公共成员具有驼峰式名称(使用pascal-case)不是常规的。 This would be more idiomatic:这会更惯用:

public class Item
{
    public string Number { get; set; }
    public string Supplier { get; set; }
    public string Place { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM