Filtering entries using IEnumerable.Select

In an ASP.NET MVC 4 project, I have a model to attach ( with a 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 out all the active members of the league. So, in the League model, I created a property similar to 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 is returning a collection with a size equal to the size of all Members (with zero values ​​for inactive members).

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

+8
c # linq asp.net-mvc anonymous-methods entity-framework
source share
2 answers

Just remove your ternary state within the selection 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
source share

But it looks like it is returning a collection with a size equal to the size of all members (with zero values ​​for inactive members).

Because you specifically say that it is. In the code, you indicate that the request returns an instance of Member if the member is active OR a null if the element is NOT active.

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

Can you leave with an expression ? and just execute:

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

All Articles