[英]Comparing two string arrays in C#
Say we have 5 string arrays as such: 假设我们有5个字符串数组:
string[] a = {"The","Big", "Ant"};
string[] b = {"Big","Ant","Ran"};
string[] c = {"The","Big","Ant"};
string[] d = {"No","Ants","Here"};
string[] e = {"The", "Big", "Ant", "Ran", "Too", "Far"};
Is there a method to compare these strings to each other without looping through them in C# such that only a and c would yield the boolean true? 有没有一种方法可以将这些字符串相互比较而不用在C#中循环它们,这样只有a和c会产生布尔值true? In other words, all elements must be equal and the array must be the same size? 换句话说,所有元素必须相等,并且数组必须是相同的大小? Again, without using a loop if possible. 同样,如果可能的话,不使用循环。
你可以使用Linq:
bool areEqual = a.SequenceEqual(b);
尝试使用Enumerable.SequenceEqual :
var equal = Enumerable.SequenceEqual(a, b);
If you want to compare them all in one go: 如果你想一次性比较它们:
string[] a = { "The", "Big", "Ant" };
string[] b = { "Big", "Ant", "Ran" };
string[] c = { "The", "Big", "Ant" };
string[] d = { "No", "Ants", "Here" };
string[] e = { "The", "Big", "Ant", "Ran", "Too", "Far" };
// Add the strings to an IEnumerable (just used List<T> here)
var strings = new List<string[]> { a, b, c, d, e };
// Find all string arrays which match the sequence in a list of string arrays
// that doesn't contain the original string array (by ref)
var eq = strings.Where(toCheck =>
strings.Where(x => x != toCheck)
.Any(y => y.SequenceEqual(toCheck))
);
Returns both matches (you could probably expand this to exclude items which already matched I suppose) 返回两个匹配项(您可以扩展它以排除已经匹配的项目,我想)
if you want to get array data that differ from another array you can try .Except 如果你想获得与另一个数组不同的数组数据,你可以尝试.Except
string[] array1 = { "aa", "bb", "cc" };
string[] array2 = { "aa" };
string[] DifferArray = array1.Except(array2).ToArray();
Output: {"bb","cc"} 输出: {“bb”,“cc”}
if (a.Length == d.Length)
{
var result = a.Except(d).ToArray();
if (result.Count() == 0)
{
Console.WriteLine("OK");
}
else
{
Console.WriteLine("NO");
}
}
else
{
Console.WriteLine("NO");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.