user2783193
user2783193

Reputation: 1012

select user under certain criteria (if exists in the list)

I have property Users of type List; I'm using List Exists method to check if this list contains object with equal property name with one passed as parameter.

public User SomeAction(User user)
{
   List<User> users = GetUsers();
   if(users.Exists(x => x.Name == user.Name))
   {
      // select user which exist under above criteria
   }
}

My question is what statement to use to select user under above criteria?

Upvotes: 1

Views: 85

Answers (6)

Nico
Nico

Reputation: 12683

Use the Any Statement.. This will return true if the statement matches any objects.

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.any.aspx

if(users.Any(x=>x.Name == user.Name)){
  //....
}

EDIT: Missed the part requiring the user to select the user after checking if it exists. In the case where you want to select the first match for an expression.

var match = users.FirstOrDefault(x=>x.Name.Equals(user.Name));
if(match != null){
   //...TODO
}

Upvotes: 2

Guru Stron
Guru Stron

Reputation: 141845

User user = users.FirstOrDefault(x=>x.Name == user.Name)
if(user != null)...

Upvotes: 1

David Pilkington
David Pilkington

Reputation: 13620

users.Single(x=>x.Name == user.Name)

A few other things try use String.Equals instead

users.Single(x=>String.Equals(x.Name, user.Name))

Upvotes: 1

Tigran
Tigran

Reputation: 62246

May be like this:

users.Where((x=>x.Name == user.Name).SingleOrDefault();

and in general can refactor your code to:

List<User> users = GetUsers();
var foundUser =  users.Where((x=>x.Name == user.Name).SingleOrDefault();
if(foundUser != null) {
  //DO SOMETHING AS THERE IS A USER
}

So avoid double query.

Note: here I assumed that User is a reference type, so it's default value is null.

Upvotes: 1

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

Use single, to get only one user and get exception if there is more than one user with same name

var user = users.Single(x=>x.Name==user.Name);

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Use FirstOrDefault - it returns null if user matching your criteria not exists, otherwise it returns matching user:

users.FirstOrDefault(u => u.Name == user.Name)

Also you can use SingleOrDefault if there should be exactly one user which matches your criteria.

Upvotes: 1

Related Questions