简体   繁体   中英

LINQ: Remove items from IQueryable

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?

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

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

你不需要foreach就可以使用这个......

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

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 Where before the Take if you want other items to replace the ones filtered out, but that means more calls to isDomainBlacklisted of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM