0

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.

6 Answers 6

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

Like so...

results.Where(r=>list1.Contains(r.id))

2 Comments

I stand by this as the solution to your described problem
i stand corrected, there was another issue causing problem which i will ask about separtely.
4
results = results.Where(r => list1.Contains(r.id));

2 Comments

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...
i stand corrected, there was another issue causing problem which i will ask about separtely.
2

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));

1 Comment

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.
0

Maybe you want this then?

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

Comments

0

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  )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.