List. Check items

S

shapper

Hello,

I have a list of an enumeration: List<Role> Roles.

Consider Role as an enumeration with the values: A, B, C, D, E, F

The list Roles should always include one but ONLY one of the values:
A, C or F.

How can I check if a list includes exactly one of these 3 values?

Thanks,
Miguel
 
G

Göran Andersson

shapper said:
Hello,

I have a list of an enumeration: List<Role> Roles.

Consider Role as an enumeration with the values: A, B, C, D, E, F

The list Roles should always include one but ONLY one of the values:
A, C or F.

How can I check if a list includes exactly one of these 3 values?

Thanks,
Miguel

By looping through the roles and count how many there are.

if (Roles.Count(r => r == Role.A || r == Role.C || r == Role.F) == 1) {
...
}

If the list is large you could make it more efficient by using a regular
loop instead and break out of the loop as soon as you find the second
occurance.
 
S

shapper

By looping through the roles and count how many there are.

if (Roles.Count(r => r == Role.A || r == Role.C || r == Role.F) == 1) {
    ...

}

If the list is large you could make it more efficient by using a regular
loop instead and break out of the loop as soon as you find the second
occurance.

Hi,

I am using the following:

public IList<Role> Roles {
get { return _Roles; }
set {
if (value.Count(r => r == Role.Other || r == Role.Admin || r
== Role.Coll) == 1)
_Errors.Add("Roles", "Choose one of the following roles:
Other, Admin or Coll");
_Roles = value;
}
} IList<Role> _Roles;

I am getting the error:
Non-invocable member
'System.Collections.Generic.ICollection<MyApp.Account.Role>.Count'
cannot be used like a method

What am I doing wrong?

Thanks,
Miguel
 
S

shapper

Hi,

I am using the following:

    public IList<Role> Roles {
      get { return _Roles; }
      set {
        if (value.Count(r => r == Role.Other || r == Role.Admin || r
== Role.Coll) == 1)
          _Errors.Add("Roles", "Choose one of the following roles:
Other, Admin or Coll");
        _Roles = value;
      }
    } IList<Role> _Roles;

I am getting the error:
Non-invocable member
'System.Collections.Generic.ICollection<MyApp.Account.Role>.Count'
cannot be used like a method

What am I doing wrong?

Thanks,
Miguel

Oops, I forgot to add System.Linq. It is solved.

Thanks,
Miguel
 

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. Add, Remove. 1
Sring[] to List<MyEnumeration> 5
List. How can I join them? 1
List Join?? How can I do this? 1
Intersection of Lists 5
Add item at start 5
Generics 7
Linq query 3

Top