views:

433

answers:

3

I'm using LINQ to SQL like:

var b =  
   from s in context.data  
   select new  
   {   
     id = s.id,  
     name = s.name  
     myEnumerable = s.OneToMany
   };

Where myEnumerable is of type IEnumberable<T> and I want to now get a subset of b based upon properties of the individual items of myEnumerable. For example, say <T> has properties Berry and BerryID, I would want to do something like:

b = 
   from p in b
   where //p.myEnumerable.myType.BerryID== 13
   select p;

I'm feel like I'm missing something easy...

+2  A: 

Are you looking to select p if any of the items in p.myEnumerable have BerryID equal to 13?

b = from p in b
    where p.myEnumerable.Any(t => t.BerryID == 13)
    select p;

Or are you looking to select p if all of the items in p.myEnumerable have BerryID equal to 13?

b = from p in b
    where p.myEnumerable.All(t => t.BerryID == 13)
    select p;

What exactly is the condition you want the items in p.myEnumerable to fulfill before you select p?

Joren
+1 good call with the Any/All..cleaner looking too than mine.
CSharpAtl
+1  A: 

Keep only items with at least one item having BerryID equal to 13 in the collection.

 var b = context.data
     .Where(s => s.OneToMany.Any(i => i.BerryID == 13))
     .Select(s => new { id = s.id, name = s.name, myEnumerable = s.OneToMany });

Keep only items with all item having BerryID equal to 13 in the collection.

 var b = context.data
     .Where(s => s.OneToMany.All(i => i.BerryID == 13))
     .Select(s => new { id = s.id, name = s.name, myEnumerable = s.OneToMany });
Daniel Brückner
+1  A: 

Since myEnumerable is an IEnumerable you will have to do a where on that.

var filteredData = from p in listOfData
                               where p.InnerData.Where(b=>b.ID == 13).Count() > 0
                               select p;

If I understand what you are saying...this is if there is an ID = 13 in the Enumerable at all.

CSharpAtl
You can shorten Where(condition).Count() to Count(condition). Further Any(condition) is faster then Count(condition) > 0 because Any() can stop after the first positive match while Count() must always process the complete sequence.
Daniel Brückner