Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 764
tsilb Avatar asked Apr 04 '09 01:04

tsilb


2 Answers

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

obj.RemoveAll(act => isDomainBlackListed(ref dc, act.Referrer));
like image 161
bytebender Avatar answered Nov 10 '22 03:11

bytebender


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.

like image 30
Guffa Avatar answered Nov 10 '22 02:11

Guffa