检查两个逗号分隔的字符串是否相等(对于内容集)

时间:2012-11-29 16:44:30

标签: c# linq

我有四个字符串,如下所示。虽然它们具有不同的字符顺序和逗号后的不同间距 - 但它们被认为具有same business value

  1. 如何检查所有字符串是否相同(根据上面解释的业务情景)?我有以下代码,但在逗号后的空格情况下失败。
  2. Enumerable.SequenceEqual
  3. 更好的方法(为此目的)

    注:“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?

    参考

    1. Best way to check for string in comma-delimited list with .NET?
    2. Compare two List<T> objects for equality, ignoring order
    3. Why does the IEnumerable<T>.Select() works in 1 of 2 cases ? Can not be inferred from usage
    4. What is the shortest code to compare two comma-separated strings for a match?
    5. Split a separated string into hierarchy using c# and linq
    6. Count matching characters between two strings using LINQ
    7. Usinq Linq to select items that is in a semi-comma separated string?
    8. Determine whether two or more objects in a list are equal according to some property

1 个答案:

答案 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);