比较 C# 中的两个逗号分隔列表以获得差异

Compare two comma separated lists in C# to get difference

如果我有两个都是逗号分隔值的字符串,并且我知道其中一个字符串只会丢失 1 个部分,我如何在 C# 中检索它?

示例:

    String 1 = "one,two,four"
    String 2 = "one,two,three,four"
    Result = "three"

我试过使用 String.Compare which returns -1 or 1 所以我知道它们是不同的,但我如何真正提取差异的值?

我想要一个包含字符串 1 中缺失值的第三个字符串

提前致谢。

您必须将字符串转换为序列 (IEnumerable<string>)。一旦你有了它,你就可以使用 Except()。最简单的方法是 String.Split(),虽然我真的 讨厌 这个方法......很多边缘情况都可能失败,性能甚至不是很好.引入实际的 CSV 解析器要好得多。但为了 Stack Overflow 的简洁起见:

var string1 = "one,two,four";
var string2 = "one,two,three,four";

var Result = string.Join(",", string2.Split(',').Except(string1.Split(',')));

在此处查看它的工作原理:

https://dotnetfiddle.net/l6AkOr

string result = null; 
string[] arr1 = 1.Split(','); //Get the first string into array
string[] arr2 = 2.Split(','); //Get the second string into array

//Compare lengths, if arr1 is bigger call Except on it, else on arr2
//Linq .Except will return elements of array which aren't in the parameter array
if(arr1.Length > arr2.Length 
{ 
    result = String.Join(" ", arr1.Except(arr2).ToArray()); 
} 
else 
{ 
    result = String.Join(" ", arr2.Except(arr1).ToArray());
}

使用 linq Except both ways 和 union 来获取两者的差异。

String[] strs1 = "one,two,four".Split(",");
String[] strs2 = "one,two,three,four".Split(",");
var res = strs1.Except(strs2).Union(strs2.Except(strs1));
String result = String.Join(",",res);

@Olivier Rogier 已经给出了很好的答案。这是一些代码来理解这个概念(他的效率更高)。

var split1 = String1.Split(",");
var split 2 = String2.Split(",");
var builder = new StringBuilder();
//other ways to do this, but aiming for illustration of the concept
List<string> list1;
List<string> list2;
if(split1.Length > split2) {
list1 = split1.ToArray();
list2 = split2.ToArray();
}
else {
list2 = split1.ToArray();
list1 = split2.ToArray();
}
foreach(var s in list1)
{
    if(!list2.Contains(s))
    {
        if(builder.Length > 0)
        {
            builder.Append(",");
        }
        builder.Append(s);
    }
}

这将为您生成一个或多个项目的列表(如果有 2 个或更多,则以逗号分隔)。我做的是freeform,所以可能有错字,所以debug。

了解其工作原理后,请阅读@Olivier Rogier 对您的 post 发表的评论。