C# 使用 IEnumerable.Select 过滤记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16227965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filtering records with IEnumerable.Select
提问by Annie
In ASP.NET MVC 4 project, I have a model for join (with payload):
在 ASP.NET MVC 4 项目中,我有一个 join 模型(带负载):
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:
我试图拉动联盟的所有活跃成员。所以,在 League 模型中,我创建了一个这样的属性:
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).
但看起来它返回一个大小等于所有大小的集合Members(非活动成员的值为空)。
Is there a better way to apply filter in anonymous method to avoid nulls?
有没有更好的方法在匿名方法中应用过滤器来避免空值?
采纳答案by lexeRoy
Just remove your ternary condition within Select Method.
只需在 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);
}
}
回答by von v.
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 Memberinstance is the member is active OR a nullif the member is NOT active.
因为你特别告诉它这样做。在您的代码中,您告诉查询返回一个Member实例是成员处于活动状态还是 anull如果成员处于非活动状态。
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);

