views:

29

answers:

2

I'd like to pass a function to LINQ queries to do operations on existing data. For eg. I have this function:

string doStuff(Product prod)
{
   return string.Format("{0} - {1}", prod.f1, prod.s2);  
}

When requesting products, i'd like to pass in this function so it returns this string and assign it to a product property NewString.

An example of the POCO object the repository returns:

class Product
{
    public string NewString{get; set;};
    public string f1 {get; set;};
    public string s2 {get; set;};
}

//Service layer
public IList<Product> GetProducts()
{
     //I currently have this:
     return _repository.GetProducts().ToList();
     //OR, is something like this possible?
     return _repository.GetProducts().Select(p => p.NewString = doStuff(p));

 }

All methods in the repository returns IQuerable<Product>

So basically, I want to generate a new string from existing data from the service layer. How do I accomplish this without looping through the returned list of objects?

A: 
//Service layer
public IList<Product> GetProducts()
{
    return _repository
        .GetProducts()
        .Select(p => new Product {
            NewString = doStuff(p),
            f1 = p.f1,
            s2 = p.s2
        })
        .ToList;
}
Darin Dimitrov
Product has over 15 properties, am I going to have to write out all of them? I already did all that assignment in the repository. I just need to assign doStuff to NewString.
Shawn Mclean
+1  A: 

If it is calculated based on Product fields and is needed where Product is needed, why not just add this function call to the NewString getter?

Andrey Shchekin