C# LINQ:从 IQueryable 中删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/716247/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:16:30  来源:igfitidea点击:

LINQ: Remove items from IQueryable

c#linqlinq-to-sqlcollectionsiterator

提问by tsilb

I want to remove an item from the result of a LINQ query before using it to databind. What is the proper way to do this?

我想在使用它进行数据绑定之前从 LINQ 查询的结果中删除一个项目。这样做的正确方法是什么?

The foreach in my illustration is the topic of my question. Illustration:

我插图中的 foreach 是我的问题的主题。插图:

var obj =
    (from a in dc.Activities
    where a.Referrer != null
    && a.Referrer.Trim().Length > 12
    && a.Session.IP.NumProblems == 0
    && (a.Session.UID == null || a.Session.UID < 1 || a.Session.User.BanLevel < 1)
    select a)
    .Take(int.Parse(ConfigurationManager.AppSettings["RecentItemQty"]));
foreach (Activity act in obj)
    if (isDomainBlacklisted(ref dc, act.Referrer))
        obj.Remove(act);

采纳答案by bytebender

You don't need the foreach you could just use this...

你不需要 foreach 你可以使用它......

obj.RemoveAll(act => isDomainBlackListed(ref dc, act.Referrer));

回答by Guffa

You can just put it at the end of the query to filter them out before they even end up in the result:

您可以将它放在查询的末尾以在它们最终出现在结果中之前将它们过滤掉:

var obj =
   (from a in dc.Activities
   where a.Referrer != null
   && a.Referrer.Trim().Length > 12
   && a.Session.IP.NumProblems == 0
   && (a.Session.UID == null || a.Session.UID < 1 || a.Session.User.BanLevel < 1)
   select a)
   .Take(int.Parse(ConfigurationManager.AppSettings["RecentItemQty"]))
   .Where(a => !isDomainBlacklisted(ref dc, a.Referrer));

You can put the Wherebefore the Takeif you want other items to replace the ones filtered out, but that means more calls to isDomainBlacklisted of course.

如果您希望其他项目替换过滤掉的项目,您可以将其放在Where前面Take,但这当然意味着对 isDomainBlacklisted 的更多调用。