Filtering records with IEnumerable.Select

anonymous-methods asp.net-mvc c# entity-framework linq

Question

In ASP.NET MVC 4 project, I have a model for join (with payload):

public class LeagueMember
{
    [Key, Column(Order = 0)]
    public int MemberId { get; set; }

    [Key, Column(Order = 1)]
    public int LeagueId { get; set; }

    public bool? IsActive { get; set; }

    [Required]
    public virtual League League { get; set; }

    [Required]
    public virtual Member Member { get; set; }

}

I am trying to pull all the active members of the league. So, in League model, I created a property like this:

public virtual ICollection<LeagueMember> LeagueMembers { get; set; }

public IEnumerable<Member> GetActiveMembers
{
    get
    {
        return LeagueMembers.Select(a => a.IsActive == true ? a.Member : null);
    }
}

But it looks like it returns a collection with size equals to that of all Members (with null values for the inactive members).

Is there a better way to apply filter in anonymous method to avoid nulls?

1
9
5/23/2017 12:01:51 PM

Accepted Answer

Just remove your ternary condition within Select Method.

public IEnumerable<Member> GetActiveMembers
{
    get
    {
        return from activeMember in LeagueMembers
               where activeMember.IsActive == true
               select activeMember.Member;
        //return LeagueMembers.Select(a => a.IsActive == true);
    }
}
4
4/26/2013 3:02:38 AM

Popular Answer

But it looks like it returns a collection with size equals to that of all Members (with null values for the inactive members).

Because you are specifically telling it do so. In your code you are telling the query to return a Member instance is the member is active OR a null if the member is NOT active.

return LeagueMembers.Select(a => a.IsActive == true ? a.Member : null);

You can go away with the ? expression and simply do a:

return LeagueMembers
    .Where(a => a.IsActive.GetValueOrDefault(false))
    .Select(o=>o.Member);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow