如何在LINQ查询中从Dictionary中获取新Object的值

本文关键字:获取 Object 的值 Dictionary LINQ 查询 | 更新日期: 2023-09-27 18:22:14

我有一个数据集和字典:

  • 集合句柄学生数据
  • 字典保存学生课程

我想从字典中获取课程名称,并将其作为CourseName输入。

private viod GenerateStudentDetails(Student studentData)
{
    var courses = m_courses.GetCoursesDictionary(); // returns Dictionary<Guid,string>()
    var studentDetails= from data in studentData
            select new
            {
                FirstName = data.FirstName, 
                LastName = data.LastName,
                Email = data.Email,
                Mobile = data.Profile.Mobile,
                City = data.Profile.City,
                PostCode = data.Profile.PostCode,
                CourseName = courses[data.Profile.CourseID ?? Guid.Empty]
            };
}

LINQ to Entities无法识别方法"System.String get_Item(System.Guid)"方法,并且此方法无法转换为存储表达式。

如何在LINQ查询中从Dictionary中获取新Object的值

您可以尝试以下方法:

private viod GenerateStudentDetails(Student studentData)
{
    var courses = m_courses.GetCoursesDictionary(); // returns Dictionary<Guid,string>()
    var studentDetails= (from data in studentData
                         select new
                         {
                             FirstName = data.FirstName, 
                             LastName = data.LastName,
                             Email = data.Email,
                             Mobile = data.Profile.Mobile,
                             City = data.Profile.City,
                             PostCode = data.Profile.PostCode,
                             CourseID = data.Profile.CourseID
                         }).AsEnumerable()
                           .Select(item=>new
                         {  
                             FirstName = item.FirstName, 
                             LastName = item.LastName,
                             Email = item.Email,
                             Mobile = item.Profile.Mobile,
                             City = item.Profile.City,
                             PostCode = item.Profile.PostCode,
                             CourseName = courses[item.Profile.CourseID ?? Guid.Empty]
                         });
}

怎么了?

问题是您创建的匿名类型中的最后一个表达式

 CourseName = courses[data.Profile.CourseID ?? Guid.Empty]

不能在这个地方,因为它不能被适当地翻译。所以你有这个选择。您可以从studentData中声明您想要的数据序列,然后进行任何转换,将您想要的任何东西调用为我们创建的新匿名类型。

仅供思考

var eCourses = ((IEnumerable<KeyValuePair<Guid, string>>) courses);
var studentDetails = (from data in studentData
                        select new
                        {
                            data.FirstName,
                            data.LastName,
                            data.Email,
                            data.Profile.Mobile,
                            data.Profile.City,
                            data.Profile.PostCode,
                            CourseName = eCourses.FirstOrDefault(s => s.Key == data.Profile.CourseID).Value
                        });