Returning typed or anonymous object using Linq
I would like to use LINQ in our project but so far I have not been able to achieve a simple task that is essential to work within the architecture of our application. All I want to do is return an object (typed IEnumerable or better Anonymou type) from the function that resides inside the business layer.
Background:
Currently, the function in Business Layer is fetching the data from Data Access Layer and returning a dataset. The business Layer function also combines data from 2 seperate datasets and the way its done currently is a bit ineffecient (using loops and updating corresponding columns). LINQ has some excellent capabilities of handling and merging multiple datasets, hence it appears ideal for the situation. Anyways, merging dataset is secondary. I would like to find how to return a LINQ object first!! Most implementations I see are straight LINQ plugins in the page code behind. This is convenient but perhaps not the most practical and acceptable solution.
Thank you!!
Hello,
A clean separation is still possible with Linq. You can't use annoymous types as they only have method scope but what you can do is define your own class and have Linq return the objects of that type.
The following code snippet is an example of how to return a known object from a Linq query. This then returns a generic list of known objects to the calling method. This could then be bound to a UI element or processed any way you require - even by another linq query....
Code Snippet
class
Program {
static void Main(string[] args) {
List<CustomerContact> customersToCall = GetAllCustomers("UK");
foreach (var c in customersToCall)
{
Console.WriteLine("{0}\t{1}", c.ContactName, c.Phone);
}
Console.ReadLine();
}
private static List<CustomerContact> GetAllCustomers(string country)
{
NorthwindDataContext db = new NorthwindDataContext();
db.Log = Console.Out;
var query = from c in db.Customers
where c.Country == country
select new CustomerContact { ContactName = c.ContactName, Phone = c.Phone };
return query.ToList();
}
}
class CustomerContact
{
public string ContactName { get; set; } public string Phone { get; set; } }
Hope this meets your requirements.
Need any more help, let us know.
Cheers
Ben