2016-02-19 74 views
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); 
} 

我将如何确保不要让重复或删除重复后,我得到的数据?

+1

你为什么要费心创建列表时,可以将其转换字典呢?你为什么不做'ToDictionary'? – poke

+2

如果您得到重复项,那么这意味着数据不会产生唯一的用户。当你真的关心用户时,为什么你从那些其他表中选择? – poke

+0

@TimSchmelter并不重要,只是第一个。我得到的用户和名称,因为我显示缺席的学生,没有出现一门课程。如果学生没有在同一天为同一位老师出现2门课程,那么字典会尝试插入一个副本。 – Lahib

回答

1

我会在查询结尾进行一些更改。让我们节省空间,在您的}).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! 
相关问题