使用c#中的hashset从父列表中删除重复列表

时间:2014-03-10 00:24:56

标签: c# hashset

我有一个父List,其中包含多个子Lists。这些内部Lists包含Column个对象。

List<List<Column>> listOfAllColumns;

public class Column
{
    public string SectionName;
    public string StirrupType;
    public int StirrupSize;
    public double StirrupSpacing;
}

让我们说我的孩子Lists包含不同的Column个像这样的对象:

List1 = {c1, c1, c2}
List2 = {c1, c2, c1}
List3 = {c2, c3}
List4 = {c1,c1, c2}

List包含这些Lists

listOfAllColumns = {List1, List2, List3, List4}

现在我想要一个从listOfAllColumns列表中删除重复列表的方法。例如,它将查看上面的列表并删除list4。

List1: c1,c1,c2
List2: c1,c2,c1
List3: c2,c3
List4: c1,c1,c2 (it is equal to List1 so it is a duplicate)

我知道这可以使用LinqDistinct方法完成,但我想使用Hashset来完成。

  • 顺便说一下,顺序很重要,例如{c1,c2,c1}与{c2,c1,c1}不同。

更新1:

这是棘手的部分。子顺序在子列表中很重要,但在父列表中并不重要。所以List1:{c1,c2}和List2:{c2,c1}是不同的,但它们如何被添加到Parent List并不重要,所以listOfAllColumns:{List1,List2}和listOfAllColumns:{List2,Lis1是一回事。

以下是我尝试的代码:

Column c1 = new Column() { SectionName = "C50", StirrupType = "Tie" };
Column c2 = new Column() { SectionName = "C50", StirrupType = "Spiral" };
Column c3 = new Column() { SectionName = "C40", StirrupType = "Tie" };


List<Column> list1 = new List<Column>() { c1, c1, c2 };
List<Column> list2 = new List<Column>() { c1, c2, c1 };
List<Column> list3 = new List<Column>() { c2, c3 };
List<Column> list4 = new List<Column>() { c1, c1, c2 };


List<List<Column>> listOfAllColumns = new List<List<Column>>() { list1, list2, list3, list4 };


HashSet<List<Column>> hs = new HashSet<List<Column>>();
List<List<Column>> uniquelistOfAllColumns = new List<List<Column>>();

foreach (var c in listOfAllColumns)
{
    if (hs.Add(c))
    {
        // my logic is that hashset should recognize the duplicates in this part.
        uniquelistOfAllColumns.Add(c);
    }
}

这里有一个类似的问题: C#: Remove duplicate values from dictionary?

1 个答案:

答案 0 :(得分:1)

您应该覆盖HashSet方法ContainsEquals(您可以在其中实施有序检查)。

然后从您的parentList插入HashSet的实现。您将检查HashSet是否包含List<column>,如果不存在则插入。

Linq似乎是最好的解决方案。