1

I have a process where I identity rows in a list (unmatchedClient) then call a separate method to delete them (pingtree.RemoveNodes). This seems a little long winded and I could acheive the same thing by merely setting the value of the property "DeleteFlag" to true. But how do I set the value using linq?

var unmatchedClient = pingtree.Nodes.Where(x =>
    _application.LoanAmount < x.Lender.MinLoanAmount ||
    _application.LoanAmount > x.Lender.MaxLoanAmount ||
    _application.LoanTerm < x.Lender.MinLoanTerm ||
    _application.LoanTerm > x.Lender.MaxLoanTerm)
.Select(x => x.TreeNode)
.ToList();

pingtree.RemoveNodes(unmatchedClient);

Thanks in advance.

David
  • 15,894
  • 22
  • 55
  • 66
dotnetnoob
  • 10,783
  • 20
  • 57
  • 103
  • Consider answers to question [Assigning values inside a LINQ Select?](http://stackoverflow.com/questions/16594544/assigning-values-inside-a-linq-select/16594770#16594770) before picking a solution to your problem – Ilya Ivanov May 19 '13 at 09:10

2 Answers2

6

Like this?

pingtree.Nodes.Where(x =>
        _application.LoanAmount < x.Lender.MinLoanAmount ||
        _application.LoanAmount > x.Lender.MaxLoanAmount ||
        _application.LoanTerm < x.Lender.MinLoanTerm ||
        _application.LoanTerm > x.Lender.MaxLoanTerm)
        .Select(x => x.TreeNode)
        .ToList()
        .ForEach(n=> n.DeleteFlag = true);
undefined
  • 33,537
  • 22
  • 129
  • 198
3

But how do I set the value using linq

You don't. Period.

Linq is a query language and querying is reading.

There is a back door that some people abuse to set values. In your case it would look like:

pingtree.Nodes.Where(...)
              .Select(n => { n.DeleteFlag = true; return n; }

but this really is not done. Firstly because it is unexpected. Linq methods, including Select, are supposed to leave the source collection unchanged. Secondly because the statement itself does not do anything because of deferred execution. You'd have to force execution (e.g. by ToList()) to make it effective.

Maybe this looks like nitpicking, but when queries get a bit more complex it becomes a major point. It is not uncommon to do a projection (Select) followed by a filter (Where). You could have decided to do a filtering (where n.Deleted == false) after the projection for instance.

So, you query the objects using linq and then loop through them to do whatever needs to be done. ToList().ForEach() is one of the methods you can use to do that.

Side node: the back door that I showed would throw exceptions when using linq-to-sql or entity framework.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291