tags:

views:

139

answers:

6

how do i use the second expression to select only those with ID from the first?

 var list1= from x in objects select x.id;


 results=results.Where(r=>r.id==  ????  )

I want the results to be only those with id from listA

tia

EDIT:i stand corrected, there was another issue causing problem which i will ask about separately.

+4  A: 

Like so...

results.Where(r=>list1.Contains(r.id))
spender
Might get tricky if list1 and results contain a lot of items...
Yann Schwartz
didnt work see above
zsharp
I stand by this as the solution to your described problem
spender
i stand corrected, there was another issue causing problem which i will ask about separtely.
zsharp
+4  A: 
results = results.Where(r => list1.Contains(r.id));
BFree
didnt work see above
zsharp
What do you mean didn't work? Did you get an exception? That's exactly how it's supposed to work; if list1 is a list of ints, it then checks the int property of your object(s) in results to see if they exist in the list. I just tested it on my machine with some dummy classes and it worked perfectly. Post either the error or more code...
BFree
i stand corrected, there was another issue causing problem which i will ask about separtely.
zsharp
+2  A: 

If you want some performance (list.Contains() has an O(n) complexity) you could go with

var ids = objects.ToDictionary(o => o.id);

results.Where(o => ids.ContainsKey(o.id));
Yann Schwartz
this gave an error. should this work with linqtosql?
zsharp
Uh, no this is Linq to objects only. If you want it to be translated in SQL by lin to sql, you should specify it in the question (and in the tags).Besides, it would be helpful if you said what exact error you got.
Yann Schwartz
A: 

Maybe you want this then?

results.Where(r=> objects.Any(o => o.id == r.id) )

jarrett
+4  A: 

A bit of a guess (haven't tried running it), but:

var filteredResults = from obj in objects 
                      join result in results on obj.id equals result.id
                      select result;

Note that this should replace both the lines of code you have in your question.

Bruce
this works too, but i wonder which is more efficient?
zsharp
A: 

If You always need only the first element's ID , You can store it to variable and use it to lambda expression

var results= from x in objects select x.id;
int firstID = results.First().id ;
results=results.Where(r=>r.id==  firstID  )

Or, use directly like this:

var results= from x in objects select x.id;
results=results.Where(r=>r.id==  results.First().id  )
miti737