为什么.ToList()。鲜明的()抛出错误,但不是.Distinct()了ToList()使用LINQ查询 [英] why .ToList().Distinct() throws error but not the .Distinct().ToList() with linq query

查看:490
本文介绍了为什么.ToList()。鲜明的()抛出错误,但不是.Distinct()了ToList()使用LINQ查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能够知道之间的 LinqQuery.ToList()是不同的() LinqQuery.Distinct()的区别了ToList(); 对我来说都。看起来相同

i'm not able to know the difference between LinqQuery.ToList().Distinct() and LinqQuery.Distinct().ToList(); for me both looks same.

考虑这个示例代码

consider this sample code :

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'。一个显式转换存在(是否缺少强制转换?)

str1 shows an error as : "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)"

但STR2没有错误。

请帮我理解这两者之间的探源。
谢谢

Please help me to understand the diffrence between these two. Thanks

推荐答案

.Distinct()是一个方法经营上的的IEnumerable< T> 返回的一个的IEnumerable< T> (懒洋洋地评估)。一个的IEnumerable< T> 是一个序列:它的不是 列表< T> 。因此,如果你想用一个列表结束了,就把 .ToList()结尾。

.Distinct() is a method that operates on an IEnumerable<T>, and returns an IEnumerable<T> (lazily evaluated). An IEnumerable<T> is a sequence: it is not a List<T>. Hence, if you want to end up with a list, put the .ToList() at the end.

// 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>

有关的为什么会是这样说明,考虑下面的原油实施鲜明()

For illustration of why this is so, consider the following crude implementation of 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;
        }
    }
}

这篇关于为什么.ToList()。鲜明的()抛出错误,但不是.Distinct()了ToList()使用LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆