Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ select Top 1 from List<T>

Tags:

c#

lambda

linq

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

like image 266
abc cba Avatar asked Oct 30 '13 08:10

abc cba


2 Answers

User UserDetails = AllUser.FirstOrDefault(x => x.UserId == 5); 
like image 188
tariq Avatar answered Oct 23 '22 10:10

tariq


You can use .First()

User UserDetails = AllUser.First(x => x.UserId == 5);
like image 40
Satpal Avatar answered Oct 23 '22 12:10

Satpal