不允许在 IEnumerable> 中重复
本文关键字:string Guid IEnumerable KeyValuePair 不允许 | 更新日期: 2023-09-27 18:35:18
我正在使用linq获取数据并将数据插入IEnumerable>中。但有时我得到重复的键值对,我不想这样,因为我正在做一个 ToDictionary(pair => 对。键,对 =>对。值)在 IEnumerable 上。
这是我的代码:
public Dictionary<Guid, string> GetCitizensWithUnwarrentedAbsence(Guid counselorId, DateTime date)
{
var now = DateTime.Now;
var startInterval = Convert.ToDateTime(date.Date.ToShortDateString());
var endInterval = Convert.ToDateTime(date.Date.ToShortDateString()).AddHours(23).AddMinutes(59);
var list = (from c in _context.CitizenCounselorSet
join p in _context.ActivityLessonParticipantSet on c.Citizen.Id equals p.UserId
where c.CounselorId == counselorId
&& c.StartDate < now
&& (c.EndDate == null || (c.EndDate.HasValue && c.EndDate.Value > now))
&& p.WasUnwarrantedAbsent
&& !p.ActivityLesson.IsDeleted
&& !p.ActivityLesson.IsCancelled
&& p.ActivityLesson.From >= startInterval
&& p.ActivityLesson.From <= endInterval
select new
{
UserId = p.UserId,
UserName = p.User.FullName,
CPR = p.User.UserName
}).ToList().Select(a => new KeyValuePair<Guid, string>(a.UserId, a.UserName + " (" + EncryptionUtility.DecryptString(a.CPR).Insert(6, "-") + ")"));
return list.ToDictionary(pair => pair.Key, pair => pair.Value);
}
我如何确保在获取数据后不会获得重复项或删除重复项?
我会在查询结束时进行一些更改。让我们节省空间,并在执行主查询逻辑时从}).ToList()
开始,并重新定义其余部分以获取字典:
var yourExistingQueryLogic = ...
}).ToList();
var yourUserDictionary = yourExistingQueryLogic
.Select(x=>new {x.UserId, UserName = x.UserName+ " (" + EncryptionUtility.DecryptString(a.CPR).Insert(6, "-") + ")"}) //you can simply build an anonymous object here
.Distinct() //this will eliminate duplicates
.ToDictionary(x=>x.UserId, x=>x.UserName); // DONE!