views:

1958

answers:

2

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);
+5  A: 

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

obj.RemoveAll(act => isDomainBlackListed(ref dc, act.Referrer));
J.13.L
+3  A: 

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.

Guffa
Yep, that's what I did. Actually I put it right in the datasource= line.
tsilb