c# - The order of returning items in the resultant List when using List.Distinct() -
what items removed resultant list when distinct.tolist()
applied in following illustration? first entry (i.e. first added list) among duplicates preserved in new list being returned? if not, there way make distinct.tolist()
preserve first entry among duplicates in new list being returned?
dim values list(of integer) = new list(of integer) values.add(1) values.add(5) values.add(2) values.add(3) values.add(2) values.add(3) values.add(4) values.add(2) values.add(2) values.add(3) values.add(3) values.add(3) dim items list(of integer) = values.distinct().tolist ' display result. each integer in items console.writeline(i) next expected output: 1 5 2 3 4
this msdn page says "the distinct(of tsource)(ienumerable(of tsource)) method returns unordered sequence contains no duplicate values". there way around this?
no can't use distinct work around that. happens works expect documentation explicitly states not guaranteed. therefore implementation can change in future versions of framework cannot rely on it. method trivial write. in fact can copy the framework implementation.
again - works want not guaranteed in future.
on other hand pretty confident implementation never change cannot imagine more efficient implementation exists.
here implementation completeness (sorry it's c# , not vb.net)
public static class myenumerable { public static ienumerable<t> distinct<t>(this ienumerable<t> source) { if (source == null) { throw new argumentnullexception(nameof(source)); } var items = new hashset<t>(); foreach (t item in source) { if (items.add(item)) { yield return item; } } } }
Comments
Post a Comment