我有List
,其中包含Beam
类的实例。每个Beam
对象都有Elevation
属性。
List<Beam> Beams = new List<Beam> {Beam1, Beam2, ...};
public class Beam
{
public double Elevation;
}
现在我想创建一个包含不同高程的List<double>
。
例如,如何编写一个接受Beams列表的方法,如下所示
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};
并删除重复的高程:
listOfElevations = {0, 320,640}
答案 0 :(得分:1)
使用Linq - 特别是Enumerable.Distinct()
方法是关键:
var listOfElevations = beams.Select(x => x.Elevation) //project to Elevations
.Distinct() // pick only distinct ones
.ToList(); //make it a list
答案 1 :(得分:1)
使用LinQ非常简单:
var listOfElevations = Beams.Select(x => x.Elevation).Distinct().ToList();
您选择了Elevation的值,选择Distinct值,将其设置为List,因为它是您的预期输出。
答案 2 :(得分:1)
List<Beam> Beams = new List<Beam> {Beam1, Beam2, Beam3, Beam4};
var differentBeams = Beams.Select(b => b.Elevation).Distinct().ToList();
答案 3 :(得分:1)
使用LINQ
的另一种方法,如果您有多个属性并希望获得唯一列表,这可能很有用
beams.GroupBy(x => x.Elevation).Select(g => g.Key);
答案 4 :(得分:1)
1)使Beam实现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)使用Distinct():
var listOfElevations = Beams.Distinct().Select(x=> x.Elevation).ToList();