Reputation: 49
i tried this linq code for get questions
return (from i in db.Question
where i.Id == questionId || (i.RelatedId == questionId && i.IsAccept == isAccept)
select i)
.ToList();
I got 2 question but their order was wrong. Can I say to Linq get first where clause then second condition?
Note: First get i.Id == questionId
then get second condition rows
Note2: Id and RelatedId is Guid. I am trying to do this without order by and single query
Upvotes: 0
Views: 190
Reputation: 49
i tried this and looking work
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());
im getting all with single query and adding them to list with conditions
Upvotes: 0
Reputation: 32455
For database queries you can use asynchronous queries and combine result later, which makes code little bid more comprehensible and asynchronous queries will be executed almost simultaneously.
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();
Upvotes: 0
Reputation: 127
You can keep a variable which shows the returned row, satisfies which of your conditions. Then select the row together with this variable(here named as 'order') in an anonymous type. Finally, OrderBy your results based on your variable and Select your row.
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();
Upvotes: 2