Recently in my project, i was trying to do a LINQ union on two anonymous types. The compiler didn't seem to be happy with it. Here is what i was trying to do:
var query = (from t in taskRepository
join s in stepRepository on t.TaskID equals s.ID
where t.UserID == 420
select new{ID = t.ID,DisplayText = t.DisplayText,ReviewStepID = null
})
.Union
(from rs in reviewStepsRepository
where rs.ReviewTypeID == 2
select new{ID = null,DisplayText = rs.ReviewName,ReviewStepID = rs.ID
})
.OrderByDescending(o => o.ID);
With some research, ended up creating a class with ID,DisplayText and ReviewStepID
public class MyTask { public int? ID { get; set; } public string DisplayText { get; set; } public int? ReviewStepID { get; set; } }
And, the happy LINQ query looked like below:
var query = (from t in taskRepository join s in stepRepository on t.TaskID equals s.ID where t.UserID == 420 select new MyTask() { ID = t.ID, DisplayText = t.DisplayText, ReviewStepID = null }) .Union (from rs in reviewStepsRepository where rs.ReviewTypeID == 2 select new MyTask() { ID = null, DisplayText = rs.ReviewName, ReviewStepID = rs.ID }) .OrderByDescending(o=>o.ID);Happy LINQ'ING!!!