簡體   English   中英

Linq第2條條件命令在哪里?

[英]Linq where clause 2 condition order?

我嘗試過此linq代碼以獲取問題

return (from i in db.Question 
        where i.Id == questionId || (i.RelatedId == questionId && i.IsAccept == isAccept)
        select i)
    .ToList();

我有2個問題,但他們的順序有誤。 我可以對Linq說先獲取where子句,然后再獲取第二條件嗎?

注意:首先獲取i.Id == questionId然后獲取第二個條件行

注意2:Id和RelatedId為Guid。 我正在嘗試不按單個查詢進行排序

您可以保留一個變量,該變量顯示返回的行,滿足您的條件。 然后以匿名類型將此行與該變量(在此稱為“ order”)一起選擇。 最后,根據變量對結果進行排序,然后選擇行。

return (from i in db.Question
        where i.Id == questionId || (i.RelatedId == questionId && i.IsAccept == isAccept)
        let order = i.Id == questionId ? 1 : 0
        select new {i, order}).Orderby(a => a.order).Select(a => a.i)
    .ToList();

對於數據庫查詢,您可以使用異步查詢並在以后合並結果,這使代碼出價更容易理解,並且異步查詢幾乎同時執行。

var byIdTask = 
    db.Question.Where(question => question.Id == questionId).ToListAsync();
var relatedTask = 
    db.Question.Where(question => question.RelatedId = questionId)
               .Where(question => question.IsAccept == isAccept)
               .ToListAsync();

await Task.WhenAll(new[] byIdTask, relatedTask);

var allQuestions = byIdTask.Result.Concat(relatedTask.Result).ToList();

我嘗試了這個並尋找工作

List<Question> final = new List<Question>();
var result = (from i in db.Question where i.Id == questionId || (i.RelatedId == questionId && i.IsAccept == isAccept) select i).ToList();
final.Add(result.Where(a => a.Id == questionId).SingleOrDefault());
final.Add(result.Where(a => a.Id != questionId).SingleOrDefault());

我通過單個查詢獲取所有內容並將它們添加到具有條件的列表中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM