Home > Software design >  Linq Where clause returns everything even though I am filtering out a condition
Linq Where clause returns everything even though I am filtering out a condition

Time:06-07

I am using c# and SolrNet to return a list of games that gamers are playing.

In my c# code, I am trying to return data for PlayerHistory, where IsPlaying is true.

The database has a table for Players with a bit column (0 for false, 1 for true) for IsPlaying.

Here is my code:

var nodes = GetGamerNodes().Select(MapNode);
    Solr.AddRange(nodes);
    Solr.Commit();

private static SearchNodes MapNode(GameList node)
{
    return new SearchNodes {
        Id = node.Id.ToString(),
        GameTitle = node.Title,
        Story = node.Story,
        Published = node.Game.Published,
        PlayerHistory= node.Players.Where(e => e.Player.Current.IsPlaying).Select(e => e.Player.Name).ToArray()
    };
}

PlayerHistory is an ICollection

In my model, IsPlaying is defined like this:

public virtual bool IsPlaying { get; set; }

But it is returning PlayerHistory data for everything regardless of the value of IsPlaying.

Am I doing something wrong?

Thanks!

CodePudding user response:

Here's a little trick that has helped me at times like these.

What works for me is to make a temporary predicate like this:

bool debugGetIsPlayerPlaying(Player player)
{
    return player.Current.IsPlaying;
}

and then when you do this replacement...

private static SearchNodes MapNode(GameList node)
{
    return new SearchNodes
    {
        Id = node.Id.ToString(),
        GameTitle = node.Title,
        Story = node.Story,
        Published = node.Game.Published,
        PlayerHistory = node.Players.Where(e => debugGetIsPlayerPlaying(e.Player)).Select(e => e.Player.Name).ToArray()
    };            
}

... it gives you something you can set breakpoints on and step through to help you determine exactly what's going on in the failing Linq query. Hope this is helpful!

  • Related