开发者

Pass a function to LINQ query

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?


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?


//Service layer
public IList<Product> GetProducts()
{
    return _repository
        .GetProducts()
        .Select(p => new Product {
            NewString = doStuff(p),
            f1 = p.f1,
            s2 = p.s2
        })
        .ToList;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜