【问题标题】:why .ToList().Distinct() throws error but not the .Distinct().ToList() with linq query为什么 .ToList().Distinct() 抛出错误,但不是 .Distinct().ToList() 与 linq 查询
【发布时间】:2012-09-18 07:04:00
【问题描述】:

我无法知道 LinqQuery.ToList().Distinct()LinqQuery.Distinct().ToList(); 之间的区别看起来一样。

考虑这个示例代码 :

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

List<string> str1  = (from item in stringList
                                select item).ToList().Distinct();

List<string> str2 = (from item in stringList
                                 select item).Distinct().ToList();

str1 显示错误为:“无法将类型 'System.Collections.Generic.IEnumerable' 隐式转换为 'System.Collections.Generic.List'。存在显式转换(您是否缺少演员表?)”

但 str2 没有错误。

请帮助我了解这两者之间的差异。 谢谢

【问题讨论】:

  • "throws" 往往用于描述运行时发生的错误(通常是异常)。而这是一个编译时错误。

标签: c# linq


【解决方案1】:

.Distinct() 是一种对IEnumerable&lt;T&gt; 进行操作的方法,返回一个IEnumerable&lt;T&gt;(延迟评估)。 IEnumerable&lt;T&gt; 是一个序列:它不是 List&lt;T&gt;。因此,如果您想以列表结尾,请将.ToList() 放在末尾。

// note: this first example does not compile
List<string> str1  = (from item in stringList
                            select item) // result: IEnumerable<string>
                         .ToList() // result: List<string>
                         .Distinct(); // result: IEnumerable<string>

List<string> str2 = (from item in stringList
                             select item) // result: IEnumerable<string>
                         .Distinct() // result: IEnumerable<string>
                         .ToList(); // result: List<string>

为了说明为什么会这样,请考虑以下Distinct() 的粗略实现:

public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source) {
    var seen = new HashSet<T>();
    foreach(var value in source) {
        if(seen.Add(value)) { // true == new value we haven't seen before
            yield return value;
        }
    }
}

【讨论】:

  • 为了 str1 工作,在末尾添加“ToList()。所以它看起来像 tihs : xxx.ToList().Distinct().ToList()
  • @Marty 不受欢迎;它在中间创建了一个不必要的列表;现有的str2 代码会更好。
  • 是的,我明白了。只需将其放入,以便更好地了解如何使这项工作:)
  • 仅供参考 - 如果您处理的是对象而不是字符串,Marc 的 str2 不等同于 Marty 对 ToList().Distinct().ToList() 的评论。这取决于对象项的类型。我有一个场景,其中 Distinct() 项目与 Distinct() 选择不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多