Shapper said:
Hello,
I have a List<Role> A and a int[] B. Role has a property int ID.
I need to loop through each element in B which does not have a correspondent Role in A with ID equal to the number in B.
Something like:
foreach (int x in B.Where(A.Role.ID == B is false))
How can I do this?
Thank You,
Miguel
If Role.ID is actually a unique identifier for a Role, then you might consider
moving from a basic List<Role> to something like SortedDictionary<int, Role>
where Role.ID is the integer key of the dictionary. Then the code is pretty
trivial and straightforward.
But I am saying that however you do it you want to move from a model of:
foreach (int i in B)
{
bool found = false;
foreach (Role r in A)
{
if (r.ID == i)
found = true;
break;
}
if (!found)
DoSomething():
}
to something more like:
foreach (int i in B)
if (!c.ContainsKey(i))
DoSomething();
where c is any collection indexed by the Role.ID in which determining existence
of a given key is efficient (or at least not so ugly). A tree or hash table, in
other words.
If you don't want to change the list A itself it's still trivial to create an
auxiliary index once you have your list A:
Hashtabale h = new Hashtable()
foreach (Role r in A)
h[r.ID] = null;
The table h ends up being an index of unique Role.ID values from A.
-rick-