【问题标题】:Not allowing duplicates in IEnumerable<KeyValuePair<Guid,string>>不允许在 IEnumerable<KeyValuePair<Guid,string>> 中重复
【发布时间】:2016-02-19 12:28:48
【问题描述】:

我正在使用 linq 获取数据并将数据插入 IEnumerable>。但有时我得到重复的键值对,我不希望这样,因为我在 IEnumerable 上执行 ToDictionary(pair => pair.Key, pair => pair.Value)。

这是我的代码:

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
  • 如果您得到重复数据,则意味着数据不会产生唯一用户。当您真正关心用户时,为什么要从其他表中进行选择呢?
  • @TimSchmelter 与第一个无关。我正在获取用户和名称,因为我正在显示没有出现在课程中的缺席学生。如果学生在同一天没有为同一位老师参加 2 门课程,那么字典将尝试插入重复的课程。
  • @poke 我从其他表中选择,因为我想知道用户是否缺席。如果用户在一天内缺席了同一位老师的两门课程,那么这将导致两个条目..但我只关心显示学生一次
  • 在调用 ToDictionary() 之前调用 List 上的 Distinct()?

标签: c# .net asp.net-mvc linq


【解决方案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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2013-04-02
    • 2018-04-15
    相关资源
    最近更新 更多