Reputation: 2633
My Code is as below
List<User> UserDetails = AllUser.Where(x => x.UserId == 5).ToList();
This Code will return all User with userID=5
and store it to my list , If All user have 5 record with UserId=5
, it will store all 5 record to UserDetail
, How can I only store the first row of the record instead of all 5, because the other 4 is just redundancy from AllUser
Upvotes: 5
Views: 25916
Reputation: 5027
It seems a bit silly with four answers stating basicly the same thing, but it is dependent on what you want to happen if there is no object fulfilling your condition. Should it raise an exception? Should it continue on quietly?
public bool IsCorrectUser(User u) { return u.UserId == 5; }
// An exception should be raised when there are no matches
var firstHit = AllUser.First(IsCorrectUser);
// When it is okey not to have a match
User firstHit;
if ((firstHit = AllUser.FirstOrDefault(IsCorrectUser) != null)
{
// Use the firstHit variable
}
On a side note, I like to put the FirstOrDefault in the if
statement for readability purposes, that way I know for sure that this if statement is closely related to the presence of a certain value or values in the collection.
Sadly in C#
declaration is a statement, not an expression.
Upvotes: 0