Vahid
Vahid

Reputation: 5444

Get Distinct values out of List<Object>

I have a List that contains instances of Beam class. Each of these Beam objects has an Elevation property.

List<Beam> Beams = new List<Beam> {Beam1, Beam2, ...};

public class Beam
{
    public double Elevation;
}

Now I want to create a List<double> that contains distinct Elevations. For example how to write a method that accepts the Beams list as below

var Beam1 = new Beam { Elevation = 320);
var Beam2 = new Beam { Elevation = 320);
var Beam3 = new Beam { Elevation = 640);
var Beam4 = new Beam { Elevation = 0);

List<Beam> Beams = new List<Beam> {Beam1, Beam2, Beam3, Beam4};

And gives this removing the duplicate elevations:

listOfElevations = {0, 320,640}

Upvotes: 0

Views: 114

Answers (5)

Tomas Pastircak
Tomas Pastircak

Reputation: 2857

1) Make Beam implement IComparable:

public class Beam : IComparable
{
    public double Elevation; //consider changing this to property, btw.

    public int CompareTo(object obj) {
         if (obj == null) return 1;

         Beam otherBeam = obj as Beam;
         return this.Elevation.CompareTo(otherBeam.Elevation);
    }
}

2) use Distinct():

var listOfElevations = Beams.Distinct().Select(x=> x.Elevation).ToList();

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Another way using LINQ, this might be useful if you have more than one property and want to get an unique list

beams.GroupBy(x => x.Elevation).Select(g => g.Key);

Upvotes: 1

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13755

    List<Beam> Beams = new List<Beam> {Beam1, Beam2, Beam3, Beam4};
        var differentBeams = Beams.Select(b => b.Elevation).Distinct().ToList();  

Upvotes: 1

Saverio Terracciano
Saverio Terracciano

Reputation: 3915

Quite simple using LinQ:

var listOfElevations = Beams.Select(x => x.Elevation).Distinct().ToList();

You're selecting the values of Elevation, choosing the Distinct values, making it to a List since it's your expected output.

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160852

Use Linq - in particular the Enumerable.Distinct() method is key here:

var listOfElevations  = beams.Select(x => x.Elevation) //project to Elevations
                             .Distinct() // pick only distinct ones
                             .ToList(); //make it a list

Upvotes: 1

Related Questions