LINQ:从IQueryable中删除项目

时间:2009-04-04 01:14:06

标签: c# linq linq-to-sql collections iterator

我希望在将LINQ查询的结果用于数据绑定之前从LINQ查询的结果中删除该项。这样做的正确方法是什么?

我插图中的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);

2 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:3)

您可以将它放在查询的末尾,以便在它们最终结果之前将其过滤掉:

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));

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

相关问题