这里有一个Column
对象列表。每个Column
对象都有几个可能唯一或不唯一的属性。这是我到目前为止编写的示例代码。如何从columns
列表中删除重复项,以便在最终列表中我只有c1和c2?
Program.cs的
var pc1 = new PartialColumn { Section = "C50" };
var pc2 = new PartialColumn { Section = "C40" };
var c1 = new Column
{
X = 0,
Y = 0,
StartElevation = 0,
EndElevation = 310,
FoundationHeight = 60,
ListOfPartialColumns = new List<PartialColumn> {pc1}
};
var c2 = new Column
{
X = 600,
Y = 0,
StartElevation = 0,
EndElevation = 630,
FoundationHeight = 60,
ListOfPartialColumns = new List<PartialColumn> { pc1, pc2 }
};
var c3 = new Column
{
X = 600,
Y = 0,
StartElevation = 0,
EndElevation = 630,
FoundationHeight = 60,
ListOfPartialColumns = new List<PartialColumn> { pc1, pc2 }
};
var columns = new List<Column> {c1, c2, c3};
PartialColumn.cs
public class PartialColumn
{
public string Section { get; set; }
}
Column.cs
public class Column
{
public double StartElevation { get; set; }
public double EndElevation { get; set; }
public double X { get; set; }
public double Y { get; set; }
public List<PartialColumn> ListOfPartialColumns { get; set; }
public double FoundationHeight { get; set; }
}
更新
我想从列列表中删除重复项。如您所见,c2和c3具有相同的属性。我想删除c3。
答案 0 :(得分:2)
您的问题How can I group ...
似乎很奇怪。您似乎想要How can I select ...
。接下来,我会问您要如何分组/选择仅获取c1
和c2
。没有c1和c2共有的属性,也没有c3。
如果您想获得c2和c3,请尝试:
columns
.Where(c => c.EndElevation == 630)
回答更新的问题
很久以前,Remove duplicates in the list using linq已经回答了获取不同价值的标准方法。
您需要做的是为Column
类添加比较器,然后尝试:
var distinctColumns = columns
.Distinct(new ColumnComparer());