LINQ-ify比较检查
本文关键字:检查 比较 LINQ-ify | 更新日期: 2023-09-27 18:16:00
我有两个列表,我试图比较值,但问题是,一个是类型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比较?
这是一种方法。我把它分开了,这样更容易理解。
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}));