How to generate a unique list of items from another list using LINQ in C #

I have a list of such elements {One, Two, Three, One, Four, One, Five, Two, One}, and I need a query that accepts this list and generates a list based on only unique elements, so the returned list will be {One , Two, Three, Four, Five}.

+4
source share
7 answers

Use the Distinct statement:

var unique = list.Distinct(); 
+17
source

The Distinct statement. Here is an example on MSDN.

http://msdn.microsoft.com/en-us/library/bb348436.aspx

+5
source
  var x = new string[] {"One", "Two", "Three", "One", "Four", "One", "Five", "Two", "One"}.ToList(); var distinct = x.Distinct(); 
+3
source

It is worth noting that Distinct () will use standard methods for determining equality, which may not suit you if your list contains complex objects, rather than primitives.

There is an overload that allows you to specify IEqualityComparer to provide custom equality logic.

Learn more about how Distinct determines whether two elements are equal: http://msdn.microsoft.com/en-us/library/ms224763.aspx

+2
source

use reporting

  List<string> l = new List<string> { "One","Two","Three","One","Four","One","Five","Two","One" }; var rootcategories2 = l.Distinct(); 
+1
source

Besides the difference, as mentioned in others, you can also use a HashSet:

 List<string> distinct = new HashSet<string>(list).ToList(); 

If you are using LINQ, go with Distinct.

+1
source

Thank you for all your answers, I think I put my question wrong. I really have a complex class on which I want to compare (for Distinct) based on a specific member of the class.

 class ComplexClass { public string Name{ get; set; } public string DisplayName{ get; set; } public int ComplexID{ get; set; } } List<ComplexClass> complexClassList = new List<ComplexClass>(); complexClassList.Add(new ComplexClass(){Name="1", DisplayName="One", ComplexID=1}); complexClassList.Add(new ComplexClass(){Name="2", DisplayName="Two", ComplexID=2}); complexClassList.Add(new ComplexClass(){Name="3", DisplayName="One", ComplexID=1}); // This doesn't produce a distinct list, since the comparison is Default List<ComplexClass) uniqueList = complexClassList.Distinct(); class ComplexClassNameComparer : IEquatable<ComplexClass> { public override bool Equals(ComplexClass x, ComplexClass y) { return (x.To.DisplayName == y.To.DisplayName); } public override int GetHashCode(ComplexClass obj) { return obj.DisplayName.GetHashCode(); } } // This does produce a distinct list, since the comparison is specific List<ComplexClass) uniqueList = Enumerable.Distinct(complexClassList , new ComplexClassNameComparer()); 
0
source

All Articles