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 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?)”
but no error for str2 .
Please help me to understand the diffrence between these two.
Thanks
.Distinct()is a method that operates on anIEnumerable<T>, and returns anIEnumerable<T>(lazily evaluated). AnIEnumerable<T>is a sequence: it is not aList<T>. Hence, if you want to end up with a list, put the.ToList()at the end.For illustration of why this is so, consider the following crude implementation of
Distinct():