1

我有

List<List<string>> source

其中包含例如

{{"a","b"},{"c","d"}}

我也有一个

List<List<string>> target

其中包含例如

{{"a","b"},{"e","f"}}

什么是最简单的方法可以让我无法找到List<string>,被包含在?sourcetargettarget

这里{"c","d"}可以找到source但不是target,因此分配后target应该是

{{"a","b"},{"e","f"},{"c","d"}}
4

2 回答 2

3

与自定义比较器一起使用Linq.Union

target = target.Union(source, new MyListComparer())  // Use the custom comparer to avoid duplication of the equal sequences.
               .ToList();

使用相等比较器(如果要进行与顺序无关的比较,请使用Equals函数中的第二个选项):

public class MyListComparer : IEqualityComparer<List<string>>
{
    public bool Equals(List<string> x, List<string> y)
    {
        return x.SequenceEqual(y);  // Use this if { "a", "b" } != { "a", "b" }
        //return x.Count == y.Count && x.Count == x.Intersect(y).Count();  // Use this if { "a", "b" } == { "a", "b" }
    }

    public int GetHashCode(List<string> obj)
    {
        // GetHashCode is used to make the comparison faster by not comparing two elements that does not have the same hash code.
        // GetHashCode must satisfy the following condition
        //  (x == y) implies (GetHashCode(x) == GetHashCode(y))
        // If your are extremely lazy, you can always return 0 but then the complexity of Union will be quadratic instead of linear.
        return obj.Sum(item => item.GetHashCode());
    }
}
于 2013-01-31T14:37:59.650 回答
0

您可以使用 LINQ:

target = source.Union(target).Distinct(new YourComparer()).ToList();

然后,您将需要创建一个继承自 IEqualityComparer 的新类(有关执行此操作的示例,请参见此处),该类将执行您想要的精确比较。

于 2013-01-31T14:34:44.560 回答