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

本文关键字:字符串 列表 添加 如果 找不到 | 更新日期: 2023-09-27 17:56:55

我有

List<List<string>> source

其中包含例如

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

我还有一个

List<List<string>> target

其中包含例如

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

我可以获得source中无法在target中找到的List<string>的最简单方法是什么,包含在target中?

这里{"c","d"}可以在source中找到,但不能在target中找到,因此在赋值后,target应该是

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

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

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

您可以使用 LINQ:

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

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