我有四个字符串,如下所示。虽然它们具有不同的字符顺序和逗号后的不同间距 - 但它们被认为具有same business value
。
Enumerable.SequenceEqual
注:“A,B”将被视为“B,A,B,A,B”
注意:我将Visual Studio 2010
与.Net Framework 4
CODE
string firstString = "A,B,C";
string secondString = "C,A,B";
string thirdString = "A,B, C";
string fourthString = "C, A,B";
//Set 1 Test
List<string> firstList = new List<string>(firstString.Split(','));
List<string> secondLsit = new List<string>(secondString.Split(','));
bool isStringsSame = Enumerable.SequenceEqual(firstList.OrderBy(t => t), secondLsit.OrderBy(t => t));
Console.WriteLine(isStringsSame);
//Set 2 Test
List<string> thirdList = new List<string>(thirdString.Split(','));
List<string> fourthList = new List<string>(fourthString.Split(','));
bool isOtherStringsSame = Enumerable.SequenceEqual(thirdList.OrderBy(t => t), fourthList.OrderBy(t => t));
Console.WriteLine(isOtherStringsSame);
Console.ReadLine();
更新:
使用OrdianlIgnoreCase
忽略案例敏感性How to use HashSet<string>.Contains() method in case -insensitive mode?
参考:
答案 0 :(得分:8)
你会认为A,B等于B,A,B,A,B吗?如果是这样,你应该使用套装。如果没有,则有序序列是合适的。
编辑:现在我们知道你真的想要设置平等:
var set1 = new HashSet<string>(firstString.Split(',').Select(t => t.Trim()));
bool setsEqual = set1.SetEquals(secondString.Split(',').Select(t => t.Trim()));
如果我们在设置相等之后不是 ......
要忽略这些空格,您应该修剪它们。例如:
var firstOrdered = firstString.Split(',')
.Select(t => t.Trim())
.OrderBy(t => t);
var secondOrdered = secondString.Split(',')
.Select(t => t.Trim())
.OrderBy(t => t);
bool stringsAreEqual = firstOrdered.SequenceEqual(secondOrdered);