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.
ThanksThis 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; }
}
精彩评论