0
我正在使用linq獲取數據並將數據插入到IEnumerable>中。但有時我得到重複的keyvaluepairs,我不想這樣做,因爲我在IEnumerable上做ToDictionary(pair => pair.Key,pair => pair.Value)。不允許IEnumerable中的重複項<KeyValuePair <Guid,string>>
這是我的代碼:
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);
}
我將如何確保不要讓重複或刪除重複後,我得到的數據?
你爲什麼要費心創建列表時,可以將其轉換字典呢?你爲什麼不做'ToDictionary'? – poke
如果您得到重複項,那麼這意味着數據不會產生唯一的用戶。當你真的關心用戶時,爲什麼你從那些其他表中選擇? – poke
@TimSchmelter並不重要,只是第一個。我得到的用戶和名稱,因爲我顯示缺席的學生,沒有出現一門課程。如果學生沒有在同一天爲同一位老師出現2門課程,那麼字典會嘗試插入一個副本。 – Lahib