重複の可能性:
C#での配列の比較
私は2つの文字列配列を持っています:
string[] a;
string[] b;
a
に存在しないアイテムの数(および内容)を特定するにはどうすればよいb
ですか?.NET 2.0を使用しているため、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;
必要なことは、1 つのリストのアイテムをセットに格納し、他のコレクションにある場合はそのセットからすべてのアイテムを削除することです。これは、2 つの入れ子になったループよりも大きなデータ セットの場合、または配列の 1 つで多くの線形検索を実行するよりもはるかに高速です。
HashSet
は 2.0 には存在しないので、単に a を使用しDictionary
て値を無視します。これはハックですが、それほどひどいものではありません。
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'
}
これを試して:
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);
}
両方をリストに変換して、次のようにします。
List<string> difference = new List<string>();
foreach(string word in a)
{
if(!b.Contains(word))
difference.Add(word);
}
文字列の配列を s に変換することをお勧めしますHashSet<T>
。.NET 2.0 での使用方法については、こちら
を
参照してくださいHashSet<T>
それで
b に存在しない a のアイテムの数 (およびアイテム) を特定するにはどうすればよいですか?
--> IntersectWithはまさにそれを行います。
昔と同じように、a
との両方で項目を列挙するだけです。b
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;
}