Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list from filtering 2 lists with linq to object

I wanted to know if there is a way using Linq to object to get a list from filtering 2 other lists. I have two lists of objects A and B, they are related two each other by an atribute(Code:String). B has another atribute, Name:String.

I want to get a list of A objects that meet 2 conditions.

-All of A objects must match their A.Code atribute to any of B.Code atribute in the B List.

-B.Name must be = "yoda";

I tried with this code(and another exampeles) but it doesent seem to work and i dont know why. I am just starting with linQ.

List<A> FilteredAList = (from OneA in ListOfA
                         join  OneB in ListOfB
                         on OneA.Code equals OneB.Code
                         where OneB.Name == "yoda"
                         select  OneA).ToList<A>();

Thanks in Advance!.

like image 643
Dante Snow Avatar asked Aug 12 '13 00:08

Dante Snow


1 Answers

With your requirement, I think we should use Any method, therefore we should write method query not expression query. Of course I don't know the equivalent of Any in expression query (At least it should be short as in the method query, otherwise, it's not good). If any one knows, please leave some comment. Thanks for that.

var FilteredAList = ListOfA.Where(x=>ListOfB.Any(y=>x.Code==y.Code && y.Name=="yoda"))
                           .ToList<A>();
like image 56
King King Avatar answered Sep 21 '22 22:09

King King