Reputation: 6540
I have two string array
string[] a;
string[] b;
How can I find that the sequence of element in array a is similar to array b?
As I am using .net2.0 I can't use LINQ.
EDIT
This is what I have tried
foreach (string val2 in a)
{
foreach (string val1 in b)
{
if (val1 == val2)
{
// Values are same - continue processing
}
else
{
// Value not same -- exit }
}
}
Upvotes: 1
Views: 2370
Reputation: 3127
/// <summary>
/// Compare two string array.
/// If both null - return true ;
/// If only one is null - return false ;
/// </summary>
bool IsSequenceEqual(string[] a, string[] b)
{
if (a == null && b == null) // both null - return true
return true;
if (a == null || b == null) // only one is null - return false
return false;
if (a.Length != b.Length) // length is different - return false
return false;
// check if equal
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i])
return false;
}
return true;
}
Upvotes: 0
Reputation: 1473
If both lists are sorted you can use one of the other solutions. But if the lists are unsorted you could do the following.
Dictionary<string, byte> dict = new Dictionary<string, byte>();
foreach (string s in a)
{
dict.Add(s, 0);
}
bool same = true;
foreach (string s in b)
{
same &= dict.ContainsKey(s);
if (!same)
break;
}
You could still do simple test before this like check for equal length and such.
If you could use .NET 4.0 there's the Intersect
method for arrays.
You can then do a.Intersect(b)
and compare the length with the length of a
or b
. If that is true
then the lists are equal because all the elements of both arrays intersect. You can do a similar trick with a.Union(b)
.
EDIT Use Dictionary instead of ArrayList as suggested by phoog.
Upvotes: 0
Reputation: 75306
private bool Compare(string[] a, string[] b)
{
if (a.Length != b.Length) return false;
for (int i = 0; i< a.Length; i++)
if (a[i] != b[i]) return false;
return true;
}
Upvotes: 4
Reputation: 223267
I believe you want to see if the elements in both arrays have same value and on same index. You can have a simple method like:
public static bool IsSequenceEqual(string[] a, string[] b)
{
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i])
return false;
}
return true;
}
Upvotes: 3