【问题标题】:Combine two list<> and remove the duplicates in it [duplicate]合并两个列表<>并删除其中的重复项[重复]
【发布时间】:2015-11-29 11:18:20
【问题描述】:

我有两个列表对象。我将它们合并到一个列表中。在组合时,我需要删除重复项。 TweetID 是要比较的字段。

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(); 

我已合并这两个列表,但无法过滤掉重复项。是否有任何内置函数可以删除 List 中的重复项?

【问题讨论】:

标签: c# .net linq


【解决方案1】:

你可以使用Distinct()方法。

tweetEntity1.Concat(tweetEntity2).Distinct().ToList(); 

【讨论】:

  • 使用Union 是更好的方法,因为这种方法已经过滤掉了重复项。
【解决方案2】:

使用Union linq 扩展,

tweetEntity1.Union(tweenEntity2).ToList()

功能上等同于.ConcatDistinct 的组合,但更易于键入且运行速度更快,

【讨论】:

    【解决方案3】:

    你可以使用Union方法。

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

    但是,您首先需要为 TweetEntity 覆盖 EqualsGetHashCode

    【讨论】:

    • 或者传递一个IEqualityComparer,因为可能已经实现了相等性。
    【解决方案4】:

    您可以使用 linq Distinct 方法,但是您必须实现 IEqualityComparer&lt;T&gt;

    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();
    

    您也可以使用Union

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

    【讨论】:

    • 联合不起作用。因为我的列表对象是一个类。
    • 我不知道如何实现这个 IEqualityComparer。能否请您详细说明。
    猜你喜欢
    • 2010-11-22
    • 2017-06-05
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2016-10-24
    • 1970-01-01
    相关资源
    最近更新 更多