Why .ToList (). Distinct () throws an error, but not .Distinct (). ToList () with linq request

I can not find out the difference between LinqQuery.ToList (). Distinct () and LinqQuery.Distinct (). ToList (); it looks the same to me.

consider this code example

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 shows the error as: "It is not possible to implicitly convert the type" System.Collections.Generic.IEnumerable "to" System.Collections.Generic.List. An explicit conversion exists (are you skipping listing?) "

but there is no error for str2.

Please help me understand the difference between the two. Thanks

+7
source share
1 answer

.Distinct() is a method that works with IEnumerable<T> and returns IEnumerable<T> (lazily evaluated). IEnumerable<T> - sequence: not a List<T> . Therefore, if you want to end the list, put .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> 

To illustrate 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; } } } 
+18
source

All Articles