2013-01-31 28 views
1

添加字符串列表,如果它不能找到

List<List<string>> source 

包含例如

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

我也有一个

List<List<string>> target 

包含例如

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

什么是最简单的方法我可以得到在source无法找到target,被列入target

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

{{"a","b"},{"e","f"},{"c","d"}} 
+2

请问'{” d“,”c“}'被添加到两个? (即子列表顺序问题)? –

+0

它不会,顺序问题。 – william007

回答

0

你可以使用LINQ:

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

然后,你需要创建一个新的类它从IEqualityComparer继承而来(请参阅here以了解执行此操作的示例),它将执行所需的确切比较。

+3

你确定名单将被比较项目? –

+3

'Contains()'使用引用相等性,而不是内容的相等性......因此,如果有两个单独但相同的列表,一个在'source'中,另一个在'target'中,则这不起作用。 –

+0

有效的点。编辑。 – IronMan84

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()); 
    } 
} 
+1

这会起作用,然而'GetHashCode()'函数会将{“a”,“b”}和{“b”,“a”}看作等于列表。 –

+0

@RoyDictus GetHashCode()总是可以返回0.联盟仍然是正确的。因为GetHashCode()不需要“_(GetHashCode(x)== GetHashCode(y)_暗示_x == y_”。 –

+0

联合仍然是正确的,这是真的,但GetHashCode()的意义在于它可以唯一标识对象,因此GetHashCode(x)== GetHashCode(y)应该真的意味着x == y。这就是哈希函数的全部要点,正如MSDN所述,“哈希代码是一个数值用于*在相等测试期间识别对象*。它也可以用作集合中对象的索引。“。 –

相关问题