Reputation: 387
I trying make if Arraylist all values contains in other arraylist (all values)
Arraylist one:
Name
Item
ArrayList two:
Item
Name
Count
Note: the lists are shuffled
I tried this:
foreach (string str1 in arraylistone)
{
if (arraylisttwo.Contains(str1))
{
//return true;
}
}
But it says true if contains someone element
Upvotes: 0
Views: 58
Reputation: 7803
There are many ways to skin a cat. Here is one using Linq's Join
extension method:
var list1 = new[] { "Name", "Item" };
var list2 = new[] { "Item", "Name", "Count" };
var join = list1.Join(list2, l1 => l1, l2 => l2, (l1, l2) => new { l1, l2 });
var allContained = join.Count() == list1.Count();
Just be careful with comparison of strings. There is an overload that takes an IEqualityComparer<TKey>
to allow you to define how the keys are compared.
Update:
As Alex Leo has pointed out, you can use Intersect
:
var allContained = list1.Intersect(list2).Count() == list1.Count();
Much simpler and it also provides an IEqualityComparer<T>
overload.
Upvotes: 1
Reputation: 655
Try something like this
var arrayOne = new string[4];
arrayOne[0] = "Item1";
arrayOne[1] = "Item2";
arrayOne[2] = "Item3";
arrayOne[3] = "Item4";
var arrayTwo = new string[4];
arrayTwo[0] = "Item1";
arrayTwo[1] = "Item2";
arrayTwo[2] = "Item3";
arrayTwo[3] = "Item4";
var allItemIsThere = true;
foreach (var one in arrayOne)
{
allItemIsThere = arrayTwo.Contains(one);
if(!allItemIsThere)
{ break;}
}
Upvotes: 1
Reputation: 2851
You could use Enumerable.Intersect.
var listA = new List<string> { "Name", "Item" };
var listB = new List<string> { "Name", "Item","Count" };
var c = listA.Intersect(listB).ToList();
Upvotes: 2