How do I return FirstName and Surname in the following class?
public static string GetAccount(int AccountId)
{
LinqSqlDataContext contextLoad = new LinqSqlDataContext();
var q = (from p in contextLoad.MyAccounts
where p.AccountId == AccountId
select new { Name = p.FirstName, Surname = p.Surname }).Single();
return ??;
}
You can return a strongly typed class, dynamic object or a tuple. I prefer to return a strongly typed class.
The problem using the dynamic type is that you dont get
intellisense and exceptions only at runtime.
The problem with a tuple is that it does not show you what you return. You or other developers have to read the method to know whats the Name and whats the Surname.
public class MyResult
{
public string Name { get; set; }
public string Surname { get; set; }
}
public static MyResult GetAccount(int AccountId)
{
LinqSqlDataContext contextLoad = new LinqSqlDataContext();
var q = (from p in contextLoad.MyAccounts
where p.AccountId == AccountId
select new MyResult{ Name = p.FirstName, Surname = p.Surname }).Single();
return q;
}
I suggest to use SingleOrDefault instead of Single. This will make sure you
get a null result if the Account does not exist instead of throw a exception.
//
select new MyResult{ Name = p.FirstName, Surname = p.Surname }).SingleOrDefault();
//
If you don't want to define a new object for your return type, you can use Tuple<string, string>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With