YHTAN
YHTAN

Reputation: 686

LINQ Query ForEach cannot use

I have a LINQ "result" of anonymuosType, inside it, it have some entity object which query by LINQ from EF.

I would like to make used of the "result" to filter and set some new value on the entity object for the "newResult".

But I not able to use the ForEach(), after the .Where() on "newResult".

May I know what I did wrong? Any alternative solution by using LINQ? (I can do simple foreach looping to achieve it, But I would like to learn more by using LINQ.)

var result = (from e in unmatch_epay_details
                                   join w in DB.WatReconDetails
                                   on e.RetTransRef equals w.RetTransRef
                                   into a
                                   from b in a.DefaultIfEmpty()
                                   select new
                                   {
                                       ePayDetailID = e.ePayReconDetailID,
                                       WATStatus = (b == default(WatReconDetail)) ? 0 : 1,//** if default return 0.
                                       EpayInfo = e,
                                       WATinfo = b
                                   })
                                   .OrderBy(a => a.ServerTransDateTime)
                                  .ToList();


var newResult = result
        .Where(a => a.EpayInfo.condition =="condition")
        .ForEach(b => b.EpayInfo.result=="result");//I not able to use the foreach at here.

Upvotes: 0

Views: 823

Answers (2)

Hans Kilian
Hans Kilian

Reputation: 25144

Like others have pointed out, ForEach works on Lists but not on IEnumerables. You can define your own ForEach extension that works on IEnumerable like this

 public static class MyExtension
 {
      public static void ForEach<T>(this IEnumerable<T> data, Action<T> action)
      {
            foreach (T element in data)
            {
                 action(element);
            }
      }
 }

Upvotes: 1

Magnus
Magnus

Reputation: 46929

ForEach() is not linq, it is a function on List<T> (and you are working with IEnumerable<T>). So use normal foreach instead.

Upvotes: 3

Related Questions