Find Ints in List ...

S

Shapper

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
 
R

Rick Lones

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-
 
A

Arne Vajhøj

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?

That can be done in many different ways.

This is my suggestion that I think matches the problem description
in English decently:

foreach(int v in arr.Where(arrelm => !lst.Exists(lstelm =>
lstelm.Id==arrelm)))

Arne
 
N

not_a_commie

My experiences with SortedDictionary have not been very favorable.
It's slow. And SortedList is worse. And Hashtable is an old .NET 1.0
type. I wouldn't use any of those. Go for the newer HashSet<> class or
something from PowerCollections or QuickGraph.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

List to EntityCollection 0
Generics 7
List. How can I join them? 1
List Join?? How can I do this? 1
Intersection of Lists 5
List. Check items 3
Update Object 5
Loop an Enumeration 4

Top