【问题标题】:Return distinct elements from a sequence of words从单词序列中返回不同的元素
【发布时间】:2014-09-06 19:02:43
【问题描述】:

假设我有一个包含这样一些词的列表:

List<string> words = new List<string>{ "apple", "computer", "user", "AppLe", "USer", "photo", "USER" };

我想生成一个这样的新列表:

List<string> newWords = new List<string>{ "apple", "computer", "user", "photo" };

如何从所有多个单词中清除第一个列表(无论它们是如何写的)?

提前非常感谢, 菲利波

【问题讨论】:

    标签: c# list distinct


    【解决方案1】:

    像这样:

    List<string> newWords = words.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
    

    这样您就不会更改结果列表中的任何单词(例如,将它们设为小写)。

    您还可以使用:StringComparer.CurrentCultureIgnoreCaseStringComparer.InvariantCultureIgnoreCase,具体取决于您的文化要求。

    【讨论】:

    • 嗨,我收到一个错误,因为第一个是“System.Collections.Generic.List”,另一个是“System.Collections.Generic.IEnumerable”。 .
    • 只需在函数末尾添加对 .ToList() 的调用即可。
    • @user3283415 哦。我的错。您需要添加一个 .ToList()。 Distinct 返回IEnumerable&lt;string&gt;。我已经更新了答案。
    【解决方案2】:
    List<string> words = new List<string> { "apple", "computer", "user", "AppLe", "USer", "photo", "USER" };
    words = words.Select(x => x.ToLower()).Distinct().ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      相关资源
      最近更新 更多