c# - 如何在 LINQ 查询中从字典获取值到新对象

标签 c# asp.net .net linq

我有一组数据和字典:

  • 收集句柄学生数据
  • 字典保存学生类(class)。

我想从字典中获取类(class)名称并将其作为类(class)名称放入。

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 does not recognize the method 'System.String get_Item(System.Guid)' method, and this method cannot be translated into a store expression."

最佳答案

您可以尝试以下操作:

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]
                         });
}

What's the problem?

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

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

不能出现在这个地方,因为它无法被正确翻译。所以你有这个选择。您可以从 studentData 中声明您想要的数据序列,然后将您想要的任何内容转换为我们创建的新匿名类型。

关于c# - 如何在 LINQ 查询中从字典获取值到新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33750564/

相关文章:

c# - 如何将 EntityFramework、Repository、UnitOfWork 和 Automapper 结合到一个 MVC 应用程序中?

c# - 下面这个语句有什么问题

c# - 使用 SQLite 进行可靠的插入

asp.net - SignalR-client在短时间内发送大量请求

asp.net - 如何在web.config中配置smtp设置

.net - 为什么不能在VB.Net中开发XNA游戏?

c# - 持久计算列上的 "A dependent property in a ReferentialConstraint is mapped to a store-generated column."(首先是 EntityFramework 数据库)

c# - 发布 asp .net web 项目后项目的 dll 丢失

.net - 如何在 GDI+ (.NET) 中创建双色调插值颜色?

.net - 使用不安全代码的含义是什么