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);
You don't need the foreach you could just use this...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With