我如何在LINQ中执行此操作

时间:2009-10-29 15:12:22

标签: linq linq-to-sql

好的,我现在有了这个

public IEnumerable<roomvu_User> GetLocationUsers(
   long LocationID, 
   DateTime StartDate, 
   DateTime EndDate, 
   int StartRows, 
   int MaximumRows)
{
    using ( DataClasses_RoomViewDataContext context = Context )
    {
        IEnumerable<roomvu_LocationMapping> Mappings = 
            ( from m in context.roomvu_LocationMappings
              where ( m.LocationID == LocationID 
                 && ( StartDate <= m.EndDate && m.StartDate <= EndDate ) )
              select m ).Skip( StartRows ).Take( MaximumRows );

        List<roomvu_User> Users = new List<roomvu_User>();

        foreach ( roomvu_LocationMapping Mapping in Mappings )
        {
            roomvu_User User = ( from u in context.roomvu_Users 
                                 where ( u.ID == Mapping.UserID ) 
                                 select u ).Single();
            Users.Add( User );
        }

        return Users;
    }
}

但我讨厌foreach一点,必须有一种方法可以在单个LINQ表达式中执行此操作.....

帮助

3 个答案:

答案 0 :(得分:1)

from m in context.roomvu_LocationMappings
join u in context.roomvu_Users
on m.UserID equals u.ID
where (m.LocationID == LocationID 
          && (StartDate <= m.EndDate && m.StartDate <= EndDate))
select new { Mapping = m, User = u }

将返回包含两个属性a.Mapping的{​​{1}}序列。

答案 1 :(得分:1)

我相信这是表达你所要求的最具表现力的方式。但是,我不确定LINQ to SQL是否足够智能,可以在Single()的结果上转换GroupJoin()调用(编译器如何转换join ... into j):

public IEnumerable<roomvu_User> GetLocationUsers(
   long LocationID, 
   DateTime StartDate, 
   DateTime EndDate, 
   int StartRows, 
   int MaximumRows)
{
    using ( DataClasses_RoomViewDataContext context = Context )
    {
        IQueryable<roomvu_LocationMapping> Mappings = 
            ( from m in context.roomvu_LocationMappings
              where ( m.LocationID == LocationID 
                 && ( StartDate <= m.EndDate && m.StartDate <= EndDate ) )
              select m ).Skip( StartRows ).Take( MaximumRows );

        IQueryable<roomvu_User> Users =
              from Mapping in Mappings
              join User in context.roomvu_Users
                on Mapping.UserID equals User.ID into j
              select j.Single();

        return Users.ToList(); // Force execution
    }
}

答案 2 :(得分:0)

return 
   Mappings.ConvertAll<roomvu_User>(new Converter<roomvu_LocationMapping, roomvu_User>(a =>
    {
       return (from u in context.roomvu_Users where (u.ID == Mapping.UserID) select u).Single();
    }));

上面是在List<roomvu_LocationMapping> Mappings上使用ConvertAll linq扩展名 或

return (from m in Mappings
        let u = context.roomvu_Users.Single(u => u.ID == m.UserID)
        select u).ToList();

不是100%肯定第二个,确保它首先工作

编辑:编辑的cos!

我不知道你的db结构但是如果romvu_Users与外键相关你应该只能将select更改为

选择m.roomvu_Users).Skip(StartRows).Take(MaximumRows);

你的Linq2Sql查询中的