Dailycode.info

Short solution for short problems

Generic List Intersect VS LINQ Query

 

I needed to intersect 2 Generic List with some class objects in the lists. The 2 generic lists had the same type. The objects were self-tracking entities, that is why (I guess) the Intersect would work using the default comparer. The definition of the intersect without writing a custom comparer is: Produces the set intersection of two sequences by using the default equality comparer to compare values. So I tried a different solution using the LINQ query. Just joining the 2 lists.

List<MyEnt> favEnts = PL.GetFavoritEnts(UserID).ToList();

List<MyEnt> allEnts = PL.GetAllEnts().ToList();

 

First the intersect that wouldn’t work:, it returned 0 Ents in the returned list.

dataSource = allEnts.Intersect(favEnts).ToList();

 

Next the solution that worked fine:

var query = from a in allEnts

            join b in favEnts on a.EntID equals b.entID

            select a;

dataSource = query.ToList();

 

The query.ToList() return a list of type List<MyEnt>