2

I have two list objects. I combine them to a single list. Whilst combining I need to remove the duplicates. TweetID is the field to be compared.

List<TweetEntity> tweetEntity1 = tt.GetTweetEntity(Convert.ToInt16(pno), qdecoded, longwoeid );
List<TweetEntity> tweetEntity2 = tt.GetTweetEntity(Convert.ToInt16(pno), qdecoded);
List<TweetEntity> tweetEntity = tweetEntity1.Concat(tweetEntity2).ToList(); 

I have combined the two lists but unable to filter out the duplicates. Is there any inbuilt function to remove the duplicates in List<>?

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
Venkat
  • 1,702
  • 2
  • 27
  • 47
  • 6
    Have you tried searching for an answer? http://stackoverflow.com/questions/4031262/how-to-merge-2-listt-with-removing-duplicate-values-in-c-sharp http://stackoverflow.com/questions/3682437/combining-2-lists-and-and-remove-duplicates-output-in-a-third-list-my-attempts – SpaceSteak Sep 03 '15 at 14:42
  • 2
    This is not duplicate as here the list item is itself a complex object. The answers in the link are simple list of integer objects. – Venkat Sep 03 '15 at 15:07
  • Same idea, except you have to consider searching for properties instead of just the value. You're allowed to extrapolate more complexity from a question. – SpaceSteak Sep 03 '15 at 15:09

4 Answers4

6

You could make use of Union method.

List<TweetEntity> tweetEntity = tweetEntity1.Union(tweetEntity2).ToList();

However, you have at first override Equals and GetHashCode for TweetEntity.

Christos
  • 53,228
  • 8
  • 76
  • 108
1

You can use Distinct() method.

tweetEntity1.Concat(tweetEntity2).Distinct().ToList(); 
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
1

use the Union linq extension,

tweetEntity1.Union(tweenEntity2).ToList()

functionally equivalent to .Concat and Distinct combined but easier to type and faster to run,

Jodrell
  • 34,946
  • 5
  • 87
  • 124
0

You can use the linq Distinct method, however you'll have to implement IEqualityComparer<T>.

public class TweetEntityComparer<TweetEntity> 
{
    public bool Equals(TweetEntity x, TweetEntity y)
    {
        //Determine if they're equal
    }

    public int GetHashCode(TweetEntity obj)
    {
        //Implementation
    }
}

List<TweetEntity> tweetEntity = tweetEntity1.Concat(tweetEntity2).Distinct().ToList();

You could also alternatively use Union.

List<TweetEntity> tweetEntity = tweetEntity1.Union(tweetEntity2).ToList();
Dave Zych
  • 21,581
  • 7
  • 51
  • 66