开发者

.Net - LINQ query returning a single object?

开发者 https://www.devze.com 2023-04-07 17:35 出处:网络
Is it possible to use a LINQ 开发者_C百科query to return a single object instead of a list? User user = (from User u in users

Is it possible to use a LINQ 开发者_C百科query to return a single object instead of a list?

User user = (from User u in users 
     where u.id == 5
     select u);


Yes,

User user = (from User u in users 
    where u.id == 5
    select u).Single()

This will throw and exception if more than one element is returned by the query.

If you only want the first element:

User user = (from User u in users 
    where u.id == 5
    select u).First()

Use SingleOrDefault() and FirstOrDefault() to return null for reference types when no element exists.


Use one of:

.Single() // return a single
.SingleOrDefault() // return a single or the default value if there are no matches
.First() // return the first object it encounters that matches
.FirstOrDefault() // return the first object it encounters that matches, or the default value if no matches

.Single() and .SingleOrDefault() will throw an exception if there are multiple matches.


Or to make it even simpler:

User user = users.Single(u => u.id == 5);

If the query returns more than one, you'll need to use First, as Single throws an exception if there is more than one element in the query.


or First and FirstOrDefault.

User user = (from User u in users 
     where u.id == 5
     select u).FirstOrDefault();


dmck is correct -- the Enumerable.Single() method will accomplish this. However, by design it will throw an exception if there is more that one object in the set. If you want to avoid throwing an exception you have several other options:

  • The Enumerable.First or Enumerable.Last methods
  • The Enumerable.ToArray method immediately followed by in indexer, such as:

    User user = (from User u in users  
        where u.id == 5 
        select u).ToArray()[0];
    
0

精彩评论

暂无评论...
验证码 换一张
取 消