是否可以将此代码转换为一个LINQ查询。我本来可以发誓我曾经做过类似的事情,但是我无法弄清楚代码可能在哪里。我想执行子查询并修改所选项的值,如果一个列表具有另一个列表的值。
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);
}
我们假设在selectInstructors
列表中我有以下值:
约翰史密斯,1
Jane Doe,2
戴夫里特,3
(在我们迭代持久化教师之前,selected
布尔值是默认值false)
schedule.Instructors
类具有该日程表的持久教师列表:
约翰史密斯,1
Dave Ritter,3
现在,我要做的是在Selected
中设置任何selectInstructors
属性,其值等于schedule.Instructors
答案 0 :(得分:2)
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();
答案 1 :(得分:1)
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.
我无法理解为什么selectItem被删除然后添加。无论如何,我希望这会有所帮助。