【问题标题】:LINQ to SQL .Join syntaxLINQ to SQL .Join 语法
【发布时间】:2015-05-27 16:09:17
【问题描述】:

我正在为.JoinLINQ 方法链接语法而苦苦挣扎。
我需要使用这种语法,所以我的查询返回IQuerable 结果,而不是IEnumerable

我想用UserGroups 加入用户,并返回一个包含两个表中的字段的新对象。 这里JOIN 操作的正确语法是什么?

var q = dc.Users
    .Join(dc.UserGroups, 
          p => p.UserGroupID, 
          s => s.UserGroupID, 
          x => x.UserGroup) //what is the right syntax?
    .Where(p => p.User.DepartmentID == '123')
    .OrderBy(p => p.User.UserName)
    .Select(p => new UserStruct 
        { 
            UserID = p.UserID,  
            UserName = p.User.UserName,  
            FullName = p.User.FullName,  
            UserGroup = p.UserGroup  
        });

这里的错误是:

方法...的类型参数无法从用法中推断出来。

【问题讨论】:

  • 我还没有看到那个帖子。似乎很接近。看看我能用那个解决方案做什么。谢谢
  • 最后一个参数是Func<TOuter, TInner, TResult>,但你的lambda只有一个参数。

标签: c# linq


【解决方案1】:

类似这样的:

var q = dc.Users
    .Join(dc.UserGroups, 
          p => p.UserGroupID, 
          s => s.UserGroupID, 
          (u, g) => new { User = u, UserGroup = g}) 
    .Where(p => p.User.DepartmentID == '123')
    .OrderBy(p => p.User.UserName)
    .Select(p => new UserStruct 
        { 
            UserID = p.User.UserID,  
            UserName = p.User.UserName,  
            FullName = p.User.FullName,  
            UserGroup = p.UserGroup  
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多