【发布时间】:2012-12-12 14:27:12
【问题描述】:
我有四个字符串,如下所示。尽管它们有不同的字符顺序和逗号后不同的间距——但它们被认为具有same business value。
- 如何检查所有字符串是否相同(根据上述业务场景)?我有以下代码,但在逗号后有空格的情况下会失败。
- 有什么比
Enumerable.SequenceEqual更好的方法(为此)?
注意:“A,B”将被视为与“B,A,B,A,B”相同
注意:我使用 Visual Studio 2010 和 .Net Framework 4
代码
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?
参考:
- Best way to check for string in comma-delimited list with .NET?
- Compare two List<T> objects for equality, ignoring order
- Why does the IEnumerable<T>.Select() works in 1 of 2 cases ? Can not be inferred from usage
- What is the shortest code to compare two comma-separated strings for a match?
- Split a separated string into hierarchy using c# and linq
- Count matching characters between two strings using LINQ
- Usinq Linq to select items that is in a semi-comma separated string?
- Determine whether two or more objects in a list are equal according to some property
【问题讨论】:
-
你认为 A,B 等于 B,A,B,A,B 吗?如果是这样,您应该使用集合。如果不是,则有序序列是合适的。
-
@JonSkeet "A,B" 将被视为与 "B,A,B,A,B" 相同