我有两个列表,我正在尝试比较值,但问题是一个类型为List<string>
,另一个类型为List<SelectListItem>
。
这就是我目前所做的,它运行良好,但我觉得这样一个简单的比较检查需要很多开销。
List<SelectListItem> fullSubjects = SubRepo.GetSubjects();
//Create our custom list based off the diff
Manage.UserCustomSubjects = Manage.UserSubjects.Where(item => !StaticReferenceList.Contains(item)).ToList();
foreach (var s in Manage.UserCustomSubjects)
{
var checkval = fullSubjects.FirstOrDefault(t => t.Text == s);
if (checkval == null)
{
var additem = new SelectListItem();
additem.Text = s;
additem.Value = s;
fullSubjects.Add(additem);
}
}
此处的总体目标是创建fullSubjects
列表,而不会出现任何重复值。
关于我如何清理这个问题的建议,或者可能LINQify的比较?
答案 0 :(得分:1)
这是一种方法。我把它分开了所以它更容易理解。
List<SelectListItem> fullSubjects = SubRepo.GetSubjects();
//Create our custom list based off the diff
Manage.UserCustomSubjects = Manage.UserSubjects.Where(item => !StaticReferenceList.Contains(item)).ToList();
var diff= Manage.UserCustomSubjects.Except(fullSubjects.Select(fs=>fs.Text));
var combined=fullSubjects.Union(diff.Select(d=>new SelectListItem {Text=d,Value=d}));
缩短:
var fullSubjects = SubRepo.GetSubjects().Union(Manage.UserSubjects.Where(item => !StaticReferenceList.Contains(item)).ToList().Except(fullSubjects.Select(fs=>fs.Text)).Select(d=>new SelectListItem {Text=d,Value=d}));