tags:

views:

113

answers:

2

I'm just getting my feet wet with LINQ. Given three lists of items, this is what I've come up with to only show ClassA items that are referenced in the list of ClassB items but not in the list of ClassC items.

var uniqueClassAIDsInClassB =
     (from classB in classBList
     select classB.ClassAID).Distinct();

var uniqueClassAIDsInClassC =
     (from classC in classCList
     select classC.ClassAID).Distinct();

var classAListFiltered =
     from classA in GetClassAList()
     where uniqueClassAIDsInClassB.Contains(classA.ID)
           !uniqueClassAIDsInClassC.Contains(classA.ID)
     select classA;

The resulting list is used as a datasource for a dropdownlist. What's a cleaner/better way to do this?

+2  A: 

this looks fine to me. i don't know that you need the Distinct() call though.

You might put it into one expression, but that could be less readable:

var classAListFiltered = from classA in GetClassAList()
where (from classB in classBList select classB.ClassAID).Contains(classA.ID)....

is a little hard to read...

statichippo
+1 distinct is unnecessary and statements can be combined
AdamRalph
Hah - yeah, hadn't noticed the redundancy of the Distinct statement. Thanks for the feedback!
jball
A couple of code comments eliminated the readability problem, and this definitely looks cleaner to me now. Thanks again!
jball
+1  A: 

Your solution is fine. For efficiency, you might want to create an A.ID list first.

var uniqueClassAIDsInClassA =
     from id in uniqueClassAIDsInClassB
     where !uniqueClassAIDsInClassC.Contains(id)
     select id;

var classAListFiltered =
     from classA in GetClassAList()
     where uniqueClassAIDsInClassA.Contains(classA.ID)
     select classA;
Ray
Interesting - it certainly seems like a more lightweight way to compare the three lists, but will it really provide a substantial performance gain?
jball
The performance gain depends on the length of GetClassAList().
Ray
Currently it's about 1500 items. That could of course change over time.
jball