How to use LINQ to filter a list of items in another list and not in a third
开发者_运维知识库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?
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...
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;
精彩评论