代码之家  ›  专栏  ›  技术社区  ›  tsilb

Linq:从iQueryable中移除项

  •  5
  • tsilb  · 技术社区  · 15 年前

    我想先从Linq查询的结果中删除一个项,然后再将其用于数据绑定。正确的方法是什么?

    插图中的前臂是我问题的主题。插图:

    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 回复  |  直到 15 年前
        1
  •  8
  •   bytebender    15 年前

    你不需要前臂你可以用这个…

    obj.RemoveAll(act => isDomainBlackListed(ref dc, act.Referrer));
    
        2
  •  3
  •   Guffa    15 年前

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

    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 如果您想用其他项目替换过滤掉的项目,但这意味着当然会有更多对isdomainblocklisted的调用。