Reputation: 4265
Is it possible to convert this code into one LINQ query. I could have sworn I had done something like this before, but I cannot figure out where I might that code might be. I want to perform a sub query and modify the values of the selected items if one list has values from another.
var selectInstructors = _instructorService.GetAllNonGuestInstructors()
.Select(i => new SelectListItem()
{
Text = i.User.ToFullName(),
Value = i.Id.ToString()
}).ToList();
var selectedItems = schedule.Instructors
.Select(instructior1 => selectInstructors.FirstOrDefault(s => s.Value == instructior1.Id.ToString()))
.Where(selectedItem => selectedItem != null);
foreach (var selectedItem in selectedItems )
{
selectInstructors.Remove(selectedItem);
selectedItem.Selected = true;
selectInstructors.Add(selectedItem);
}
So let's assume in the selectInstructors
list I have these values:
John Smith, 1
Jane Doe, 2
Dave Ritter, 3
(before we iterate the persisted instructors the selected
Boolean value is a default of false)
The schedule.Instructors
class has the persisted list of instructors for that schedule:
John Smith, 1
Dave Ritter, 3
Now, what I would like to do is set any of the Selected
properties in selectInstructors
where the value is equal to schedule.Instructors
Upvotes: 0
Views: 137
Reputation: 2531
var selectedIds = schedule.Instructors.Select(i => i.Id.ToString()).ToList();
var instructors = (from instructor in _instructorService.GetAllNonGuestInstructors()
let value = instructor.Id.ToString()
select new SelectListItem()
{
Text = instructor.User.ToFullName(),
Value = value,
Selected = selectedIds.Contains(value)
}).ToList();
Upvotes: 2
Reputation: 12315
var allInstructors = _instructorService.GetAllNonGuestInstructors();
if(allInstructors!=null)
allInstructors.Select(i =>
new SelectListItem() { Text = i.User.ToFullName(), Value = i.Id.ToString() }).
Zip(schedule.Instructors,(selectedItems,instructor)=>
{var item = selectedItems.FirstOrDefault(s => s.Value == instructior.Id.ToString());
if(item!=null)
item.Selected=true;});
//Now use allInstructors collection further it will have Selected true according to your conditions.
I can't understand one thing why selectedItem is removed and then added. Anyways I hope this will help.
Upvotes: 1