2013-09-25 53 views
1

如何編寫linq查詢以從用戶以前不嘗試的問題表中檢索問題。Linq中的內部查詢

問題表

create table questions 
(
    questionID int, 
    question varchar, 
    primary key(questionID) 
); 

create table result 
{ 
    id int, 
    answered_by varchar, 
    questionid int, 
    answer varchar, 
    primary key (id), 
    foreign key (questionid) references question(questionID) 
); 
+0

是什麼你的dataContext.Are你使用entityframework這個? –

+0

http://stackoverflow.com/questions/183791/how-would-you-do-a-not-in-query-with-linq檢查這個 –

回答

2

不知道你有什麼用。

但可以使用類級別建議像下面的東西。

假設您已將所有數據從數據庫加載到列表。

var list= questionsList.Where(i => resultList.All(p => p.questionid != i.questionid)); 
0
from QUESTION in QUESTIONS 
join 
ANSWER in RESULT 
on 
QUESTION.questionID equlas ANSWER.questionid 
where 
ANSWER.answer!=NULL 
select {QUESTION.questionID, ANSWER.answered_by, ANSWER.questionid, ANSWER.answer} 
0

對於誰與一組內存中對象的啓動和正在查詢對數據庫的人,我發現這是最好的方式去:

var itemIds = resultList.Select(x => x.questionid).ToArray(); 
var results = questionsList.Where(x => !itemIds.Contains(x.questionid)); 

**This produces a nice WHERE ... IN (...) clause in SQL.** 
+0

我想你可以像這樣用單行'var x = questionsList.Where(i =>!resultList.Any(p => p.questionid == i.questionid));'' –