Return single column with Linq

2019-06-11 11:48发布

问题:

 public string GetNameBySSN(string SSN)
 {
    var results = from c in Clients
                  where c.ClientSSN.Equals(IRRCNumber)
                  select c.FirstName;
    //return results.ToString();
 }

I want to return a single column value with Linq and not sure if there is way to do a quick easy return. I commented section of code that I know does not return the value and if enumerate through collection I can get the value but wondering if a better way was around.

I do understand that Linq is Set based and that it has no upfront means know that the result is set with a single member.

回答1:

results.FirstOrDefault();

This way will not throw an exception, FYI. Where as @Mehrdad will.



回答2:

return results.First().ToString();

Other possible variants:

.First() returns the first item and throws an exception if no item exists. It ignores all other items.

.FirstOrDefault() returns the first item if exists and returns the default value of the result type if nothing exists. It ignores all other items.

.Single() returns the only item if the collection contains exactly one item and throws an exception otherwise.

.SingleOrDefault() is like .Single() but returns the default value of the result type instead of throwing an exception.