views:

156

answers:

2
 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.

+5  A: 
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.

Mehrdad Afshari
If c.FirstName is a string you dont need the ToString.
Daniel A. White
Of course. This was mentioned in the commented code and I replicated it for that matter.
Mehrdad Afshari
+5  A: 

results.FirstOrDefault();

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

Daniel A. White