I have two tables: Questions and Educations, there isn't any relation between these tables.
How can I select the combination of the last 10 (order by date) item from both these tables?
I have two tables: Questions and Educations, there isn't any relation between these tables.
How can I select the combination of the last 10 (order by date) item from both these tables?
You want something like
var result = questions.OrderByDescending(i => i.id).Take(5).Union(education.OrderByDescending(i => i.id).Take(5));
In LINQ you can't join two tables with o relationship, which would be needed to preform your query. You would be better of doing a two LINQ to SQL queries to select the last 10 of each table into similar structure, and then taking these two enumerations, doing a union and taking the last 10 of that.
If you used a structure like:
public struct QuestionsEducationsJoin
{
public DateTime date;
public int QuestionID;
public string Question;//...;
public int EducationID;
public string Education;//...;
}
You can then select from both tables into this structure:
var questionEnumeration = database.Questions
.OrderByDescending(question => question.DateField)
.Take(10)
.Select(question => new QuestionsEducationsJoin()
{
date = question.DateField;
//...
});
var educationEnumeration; //...
var outputEnumeration = questionEnumberation
.Union(educationEnumeration)
.OrderByDescending(x => x.date)
.Take(10);
The answer depends on whether or not you need the resulting list to be polymorphic (a list of objects that share a common interface exposing common properties to be manipulated) or a simple list of objects that you don't easily know how to cast.
If there are fields common to both that you want to work with, create an interface of these common attributes and have both classes implement the interface. For instance, the interface could be
Interface iBrainStuff
{
public DateTime DateCreated;
public int AreaOfExpertise;
public string Description;
}
Then you simply implement the interface in each class:
public class question: iBrainStuff
public class education: iBrainStuff
Then you create your results list
List<iBrainStuff> results = new List<iBrainStuff>();
then you
results.AddRange(context.educations.OrderByDescending(x => x.DateCreated).Take(5);
results.AddRange(context.questions.OrderByDescending(x => x.DateCreated).Take(5);
And that puts the top ten (5 from each) in the results list. And the results in the results list can all be interrogated for their iBrainStuff interface fields:
Interface iBrainStuff
{
public DateTime DateCreated;
public int AreaOfExpertise;
public string Description;
}