使用LINQ列出过滤

时间:2011-06-09 13:44:56

标签: c# .net linq

所以我在代码中遇到了这个方法:

private void FilterBasedUponPermission(List<Data.Indications.SpWeb_SavedIndications1LightDataObject> list)
        {
            list.RemoveAll(item =>
                (item.Permission == Controllers.Indications.ICConstants.TradeType_LLH && !isLLH) ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_ALM && !isALM) ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_RealEstate && !isRE) ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_Auditor && !isAuditor));
        }

但是,在传入的列表中,某些permission值为null,并且它们将保留在已过滤的列表中。我希望它删除那些也没有权限集的项目,而不仅仅是那些与您作为用户的权限不匹配的项目。

谢谢!

3 个答案:

答案 0 :(得分:7)

只需添加一个item.Permission == null

list.RemoveAll(item => item.Permission == null ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_LLH && !isLLH) ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_ALM && !isALM) ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_RealEstate && !isRE) ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_Auditor && !isAuditor));

答案 1 :(得分:1)

那些工作吗?

list.RemoveAll(item => !item.Permission.HasValue); // in case Permission is Nullable<T>
list.RemoveAll(item => item.Permission == null);

您可以在逻辑或(||)之后添加所有其他条件。

干杯, 的Matthias

答案 2 :(得分:1)

private void FilterBasedUponPermission(List<Data.Indications.SpWeb_SavedIndications1LightDataObject> list)
        {
            list.RemoveAll(item =>
                (item.Permission == null) ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_LLH && !isLLH) ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_ALM && !isALM) ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_RealEstate && !isRE) ||
                (item.Permission == Controllers.Indications.ICConstants.TradeType_Auditor && !isAuditor));
        }