delete
delete

Reputation:

How would I remove items from a List<T>?

I have a list of items.

The problem is the returned items (which I have no control over) return the same items THREE time.

So while the actual things that should be in the list are:

  1. A
  2. B
  3. C

I get

  1. A
  2. B
  3. C
  4. A
  5. B
  6. C
  7. A
  8. B
  9. C

How can I cleanly and easily remove the duplicates? Maybe count the items, divide by three and delete anything from X to list.Count?

Upvotes: 0

Views: 263

Answers (5)

Anthony Pegram
Anthony Pegram

Reputation: 126804

The quickest, simplest thing to do is to not remove the items but run a distinct query

var distinctItems = list.Distinct();

If it's a must that you have a list, you can always append .ToList() to the call. If it's a must that you continue to work with the same list, then you'd just have to iterate over it and keep track of what you already have and remove any duplicates.

Edit: "But I'm working with a class"

If you have a list of a given class, to use Distinct you need to either (a) override Equals and GetHashCode inside your class so that appropriate equality comparisons can be made. If you do not have access to the source code (or simply don't want to override these methods for whatever reason), then you can (b) provide an IEqualityComparer<YourClass> implementation as an argument to the Distinct method. This will also allow you to specify the Equals and GetHashCode implementations without having to modify the source of the actual class.

public class MyObjectComparer : IEqualityComparer<MyObject>
{
    public bool Equals(MyObject a, MyObject b)
    {
        // code to determine equality, usually based on one or more properties
    }

    public int GetHashCode(MyObject a)
    {
        // code to generate hash code, usually based on a property
    }
}

// ...

var distinctItems = myList.Distinct(new MyObjectComparer());

Upvotes: 11

vlad
vlad

Reputation: 4778

you could simply create a new list and add items to it that are not already there.

Upvotes: 0

Dave D
Dave D

Reputation: 8972

If you're using C# 3 or up:

var newList = dupList.Distinct().ToList();

If not then sort the list and do the following:

var lastItem = null;
foreach( var item in dupList )
{
    if( item != lastItem )
    {
        newItems.Add(item);
    }

    lastItem = item;
}

Upvotes: 0

fejesjoco
fejesjoco

Reputation: 11903

Linq has a Distinct() method which does exactly this. Or put the items in a HashSet if you want to avoid duplicated completely.

Upvotes: 0

Michael Sagalovich
Michael Sagalovich

Reputation: 2549

if you are 100% sure that you receive everything you need 3 times, then just

var newList = oldList.Take(oldList.Count / 3).ToList()

Upvotes: 1

Related Questions