Possible Duplicate:
Comparing Arrays in C#
I have a two string arrays:
string[] a;
string[] b;
How can I identify how many (and what) items of a
are not present in b
? As I am using .NET 2.0 so I can't use linq.
Possible Duplicate:
Comparing Arrays in C#
I have a two string arrays:
string[] a;
string[] b;
How can I identify how many (and what) items of a
are not present in b
? As I am using .NET 2.0 so I can't use linq.
List<string> result = new List<string>();
foreach (string sa in a)
{
if (Array.IndexOf(b, sa) < 0)
result.Add(sa);
}
int count = result.Count;
convert them both to a List the do something like this:
List<string> difference = new List<string>();
foreach(string word in a)
{
if(!b.Contains(word))
difference.Add(word);
}
I would recommand to transform your arrays of strings into HashSet<T>
s.
See here for how to use a HashSet<T>
in .NET 2.0
Then
How can I identify how many (and what) items of a are not present in b?
--> IntersectWith does precisely that.
Try this:
string[] a = ...;
string[] b = ...;
List<string> bList = new List<string>(b);
List<string> valuesInAButNotInB = new List<string>();
foreach (string value in a)
{
if (!bList.Contains(value))
valuesInAButNotInB.Add(value);
}
What you need to do is store the items from one list in a set, and then remove all of the items from that set if they are in the other collection. This will be much quicker for larger data sets than two nested loops, or performing lots of linear searches on one of the arrays.
Since HashSet
doesn't exist in 2.0 I just use a Dictionary
and ignore the values. It's a hack, but not a terrible one at that.
string[] a = null;
string[] b = null;
Dictionary<string, string> values = new Dictionary<string, string>();
foreach (string s in a)
{
values.Add(s, s);
}
foreach (string s in b)
{
values.Remove(s);
}
foreach (string s in values.Keys)
{
Console.WriteLine(s);//This string is in 'a' and not in 'b'
}
Just enumerate items in both a
and b
, just like in the old days:
private static void Main(string[] args)
{
string[] a = new string[] { "a", "b", "c", "d" };
string[] b = new string[] { "c", "d" };
foreach (string tmp in a)
{
bool existsInB = false;
foreach (string tmp2 in b)
{
if (tmp == tmp2)
{
existsInB = true;
break;
}
}
if (!existsInB)
{
Console.WriteLine(string.Format("{0} is not in b", tmp));
}
}
Console.ReadLine();
}
private List<string> CompareArray(string[] arr1, string[] arr2)
{
List<string> compareList = new List<string>();
//iterate throught it
foreach( string str in arr1 )
{
if(!arr2.Contains( str ))
{
compareList.Add(str);
}
}
return compareList;
}