I have the following entities:
CartoonStory
CartoonFigure
Sex
A CartoonStory is told by one or more CartoonFigures and a CartoonFigure is of a Sex male or female.
When the user of my website is for example a female I only want to ret开发者_Python百科rieve CartoonFigures with the Sex female if there are any. If this is not the case retrieve the Male CartoonFigures instead.
So I get a CartoonStory;check if there are female cartoonfigures under it;if not give the male cartoonfigures instead.
How can I do this in LINQ. Specially the part take the females if they exist if not take the males.
Thanks in Advance!
Martijn
Without knowing any details around your classes, something along these lines should work:
private static IEnumerable<CartoonFigure> GetFigures(CartoonStory story, Sex preferredSex)
{
var result = story.StoryTellerFigures.Where(cf => cf.Sex == preferredSex);
if (!result.Any())
{
result = story.StoryTellerFigures;
}
return result;
}
In other words; filter out the story teller figures with the preferred sex from the story. If none are found, just return all story teller figures from the story (they will be of the opposite sex).
Simple enough. Through this code in a partial for your CartoonStory
model.
partial class CartoonStory
{
public IEnumerable<CartoonFigure> FemalesThenMales
{
get
{
return Females.Count() > 0 ? Females : Males;
}
}
public IEnumerable<CartoonFigure> Females
{
get
{
return CartoonFigures.Where(c => c.Sex.Name == "Female");
}
}
public IEnumerable<CartoonFigure> Males
{
get
{
return CartoonFigures.Where(c => c.Sex.Name == "Male");
}
}
}
EDIT (after question author's comment):
When you're ready to search for your cartoon figures.
var figures = dataContext.CartoonStories.Where(c => c.Id == 1).FemalesThenMales;
It's very clear what's going on. I'm a big fan of breaking code into smaller, easily identifiable parts. Yes, this will be sent to the database as either one or two queries (one if females are found; two otherwise).
DON'T DO THIS!!!
var figures = dataContext.CartoonStories.Where(c => c.Id == 1).CartoonFigures.Any(c => c.Sex == "Female") ? dataContext.CartoonStories.Where(c => c.Id == 1).CartoonFigures.Where(c => c.Sex == "Female") : dataContext.CartoonStories.Where(c => c.Id == 1).CartoonFigures.Where(c => c.Sex == "Male");
One liners aren't all they're cracked up to be. :(
IEnumerable < CartoonFigure > Cfig = CartoonFigure.OrderBy(W => (W.Sex== "Female") ? 1 : 100);
If will order by Females first then Males... So if there are any Females, you will get it first.
精彩评论