views:

90

answers:

4

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.

A: 

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;
                                }
            );
Matt
+1  A: 

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(); 
Adam Robinson
The OP is looking for a list of Proposals, not Services, as your methods return.
Jay
@Jay: Thanks for the catch; edited.
Adam Robinson
Thanks a lot. You right, I wrote the sample in the moment and forget about the {} :P.I can not vote because I new, but thanks again.
santiagokci
A: 
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>.

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