3

How to change the following code to one LINQ query :

var items = (from s in db.WfRADocStates.Include(x => x.WfStateStatu)
                                       .Include(xx => xx.WfState)
                                       .Include(xxx => xxx.WfState.Dept)
                                       .Include(d => d.RADoc)
             where s.RADocID == docID
                && !s.isHistory
                && s.StatusID == 1
                && s.WfStateStatu.isToNotify
             select s).ToList();

foreach (var item in items)
{
    EmailHelper.notify(item);
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • 1
    look at [this question](http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet) and note that `LINQ` is should be used for `Q`uerying – Jonesopolis Feb 26 '14 at 04:48
  • 1
    @Jonesy `ForEach` technically isn't LINQ. It's a method on `List` not `IEnumerable` it just happens take a delegate as it's argument so it looks the same as LINQ's query syntax. Really, the `Where` is LINQ, the `Select` does nothing and the `ForEach` is just a method in `List` that is called on the results of the LINQ query. – evanmcdonnal Feb 26 '14 at 04:50
  • @evanmcdonnal are we not trying to prove the same point? – Jonesopolis Feb 26 '14 at 04:52
  • 5
    Your code is perfectly sensible as it's written. Don't change it. A query produces a *query*; a loop produces a *side effect*. Don't make a *query* that produces a *side effect*; that's not its job. A query's job is to answer a question, not do a task. A loop's job is to do a task. – Eric Lippert Feb 26 '14 at 05:47

2 Answers2

2

Use .ForEach in the LINQ :

(from s in db.WfRADocStates.Include(x=>x.WfStateStatu).Include(xx=>xx.WfState).Include(xxx=>xxx.WfState.Dept).Include(d=>d.RADoc)
         where
            s.RADocID == docID &&
            !s.isHistory &&
            s.StatusID == 1 &&
            s.WfStateStatu.isToNotifyCNH
         select s).ToList().ForEach(
                s => EmailHelper.notify(s)
         );
Maddy
  • 300
  • 1
  • 8
1

Give this a try (excluding all this include nonsense);

Collection.Where(s => s.RadocID == docID && ...).ToList().ForEach(s => EmailHelper.notify(s));
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115