简体   繁体   中英

how to remove objects from list by multiple variables using linq

I want to remove objects from a list using linq, for example:

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.

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:

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> 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). This would be more idiomatic:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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