LINQ: Remove items from IQueryable
14,696
Solution 1
You don't need the foreach you could just use this...
obj.RemoveAll(act => isDomainBlackListed(ref dc, act.Referrer));
Solution 2
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.
Author by
tsilb
Updated on June 04, 2022Comments
-
tsilb almost 2 years
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);