Home > OS >  Get one field value from LINQ query
Get one field value from LINQ query

Time:05-11

I need to get one value of the q2.RoomId in this linq query as below and pass it to string variable . and is it possible to set alias column name for select ?

var result = from q1 in _db.DormApplications
              join q2 in _db.DormRooms
              on q1.DormRoomId equals q2.Id
              where q1.Poster ==  username && q1.Review == EnableType.YES  
              && now > q1.Sdate && now <q1.Edate
              select new { q1.Name, q1.Sdate, q1.Edate, q1.DormRoomId, 
              q2.RoomId };

I tried this to get q2.RoomId ,

 String room = result[4].ToString();

but still cannot work ,please anyone can help me ?

CodePudding user response:

If you know the query will only return one row you can write:

var result = (from q1 in _db.DormApplications
              join q2 in _db.DormRooms
                on q1.DormRoomId equals q2.Id
              where 
                 q1.Poster ==  username && q1.Review == EnableType.YES  
                 && now > q1.Sdate && now <q1.Edate
              select 
                new { 
                       q1.Name, 
                       q1.Sdate, 
                       q1.Edate, 
                       q1.DormRoomId, 
                       q2.RoomId 
                    }).FirstOrDefault();
var roomId = result.RoomId;
var Name = result.Name;
  • Related