【问题标题】:Remove duplicates from a List<string> in C# [duplicate]从 C# 中的 List<string> 中删除重复项 [重复]
【发布时间】:2014-11-11 09:49:59
【问题描述】:

在 C# 中从列表中删除重复项

我有一个数据阅读器可以从数据库中读取字符串。

我使用 List 来聚合从数据库中读取的字符串,但我在这个字符串中有重复项。

任何人都有一个快速的方法来从 C# 中的通用列表中删除重复项?

List<string> colorList = new List<string>();

    public class Lists
    {
        static void Main()
        {
            List<string> colorList = new List<string>();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            colorList.Add(variableFromDB.ToString());

                    foreach (string color in colorList)
                    {
                      Response.Write(color.ToString().Trim());
                    }
        }
    }

【问题讨论】:

  • .Distinct()怎么样

标签: c# asp.net list


【解决方案1】:
colorList = colorList.Distinct().ToList();

【讨论】:

    【解决方案2】:
    foreach (string color in colorList.Distinct())
    

    【讨论】:

      【解决方案3】:
      IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);
      
      public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
          this IEnumerable<TSource> source,
          Func<TSource, TKey> keySelector)
      {
          var knownKeys = new HashSet<TKey>();
          return source.Where(element => knownKeys.Add(keySelector(element)));
      }
      

      【讨论】:

      • 为什么不只是sourceList.GroupBy(x =&gt; x.FooName).Select(x =&gt; x.First())
      【解决方案4】:

      使用 LINQ:

      var distinctItems = colorList.Distinct();
      

      类似的帖子在这里:Remove duplicates in the list using linq

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-28
        • 2015-06-20
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        • 2010-09-08
        • 2011-10-21
        相关资源
        最近更新 更多