2009-10-29 48 views
2

好吧,我現在有這個如何在LINQ做這個

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表達式來做到這一點.....

幫助

回答

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.User

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

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

不是100%地肯定了第二的ConvertAll LINQ擴展,以確保它工作第一

編輯:您編輯的COS !

我不知道烏爾數據庫結構,但如果romvu_Users與外鍵關聯,你應該只能夠選擇切換到

選擇m.roomvu_Users).Skip(StartRows)。取(MaximumRows);

在LINQ2SQL查詢

1

我相信這是代表你問了最具表現力的方式。不過,我不知道的LINQ to SQL是足夠聰明的翻譯對GroupJoin()的結果Single()調用(編譯器如何轉換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 
    } 
}