santiagokci
santiagokci

Reputation: 35

replace foreach for LINQ expression

How can I do this using LINQ?

var prop = new List<EventProposal>();
foreach (var eventProposal in @event.Proposals)
      foreach (var service in eventProposal.Services)
      {
            if (!string.IsNullOrEmpty(service.LongDescription))
            {
                  prop.Add(eventProposal);
                  break;
            }
      }

Any idea? Thanks in advance

Upvotes: 2

Views: 2676

Answers (4)

Adam Robinson
Adam Robinson

Reputation: 185613

Extension method syntax:

prop = @event.Proposals.Where(p => p.Services.Any(
           s => !string.IsNullOrEmpty(s.LongDescription)).ToList();

Or query:

prop = (from p in @event.Proposals
        where p.Services.Any(s => !string.IsNullOrEmpty(s.LongDescription))
        select p).ToList();

NOTE

The logic in your example may not be what you intended; as it stands, it will only add the item if the first Service has a non-empty LongDescription (because the break is outside the if, so it will break on the first item regardless of whether or not it fits the condition). The logic above is assuming that the example is wrong and you want to add it if any of them have a non-empty LongDescription.

If, however, that is what you want, then try this:

prop = @event.Proposals.Where(
       p => !string.IsNullOrEmpty(
       p.Services.Select(s => s.LongDescription).FirstOrDefault())).ToList(); 

Upvotes: 2

Bryan Watts
Bryan Watts

Reputation: 45445

from proposal in @event.Proposals
where proposal.Services.Any(service => !String.IsNullOrEmpty(service.LongDescription))
select proposal;

Upvotes: 0

Jay
Jay

Reputation: 57919

var prop = @event.Proposals
   .Where(proposal => proposal.Services.All(service => 
        !string.IsNullOrEmpty(service.LongDescription))))
   .ToList();

This returns all the proposals in @event where all of the proposal's services have non-null LongDescription values. The ToList() is optional, only if you want the result as IList<T> instead of IEnumerable<T>.

Upvotes: 0

Matt
Matt

Reputation: 2815

Something along these lines. Don't have the ability to compile and check this, and I don't know if it is honestly clearer than the nested foreach.

var prop = @event.Proposals.Aggregate(
           new List<EventProposal>(), 
           (list, proposal) => { list.AddRange(proposal.Services
                                               .Where(service =>
                                                !string.IsNullOrEmpty(service.LongDescription)));                                      
                                 return list;
                                }
            );

Upvotes: 0

Related Questions