1

I've a nice situation, I think at beginning this a usual query but I'm having some problem trying to solve this, the situation is:

I've a list of "Houses", and each house have a list of "Windows". And I want to filter for a catalog only the Houses witch have a Blue windows, so my extension method of House is something like:

public static List<House> FilterByWindow (this IEnumerable<House> houses, Window blueOne){

    var list = houses.Select(p=>p.Windows.Where(q=>q.Color == blueOne.Color));
    return list.ToList();
}

Is this correct or I'm losing something? Some better suggestion?

2 Answers 2

2

If you want to search for House instances containing blue Windows, then use the existing Any extension:

var blueWindowHouses =
    from h in houses
    where h.Windows.Any(w => w.Color == blueOne.Color)
    select h;

What you have right now is not correct. The Select extension does not filter - it is a projection, and you aren't assigning the result to anything, so that line you have is effectively a no-op.

Also, by wrapping this logic in a method, you can prevent the expression compiler from being able to translate it into a SQL statement. Instead, write it all in one shot, as I have above, or accept and return an IQueryable<House> instead of accepting an IEnumerable<House> and returning a List<House>.

Sign up to request clarification or add additional context in comments.

1 Comment

this solution works just fine, but now I realized that I've another business require. My final list must have just the blue windows, have some simple linq solution for that?
2
return houses.Where(house => house.Windows.Any(window => window.Color == blue))
             .ToList();

3 Comments

That will return a List<bool>
Select and Where are right next to each other on my keyboard. I always mix them up.
You have dedicated keys for Select and Where? Where can I get one of these keyboards?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.