0

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 ?

3
  • 1
    This is a list so you have multiple rooms and therefore multiple RoomIds. Do you want all or a specific one? An anonymous type deduces the name from the input names so you should actually just use RoomId as name when you have the correct Room or Rooms at hand. Commented May 10, 2022 at 8:50
  • I am sorry ,it's shouldn't to list ,because it's only get one row Commented May 10, 2022 at 9:08
  • LINQ returns IEnumeralbes (in this case) or objects (if you used FirstOrDefault), not DataTable rows. You can't access object properties or fields by index Commented May 10, 2022 at 9:26

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

5 Comments

but it's only get roomid,
I want to get this : q1.Name, q1.Sdate, q1.Edate, q1.DormRoomId, q2.RoomId
@georgetovrea do so then. Use new {} to return what you want and access the fields by name
@Magnus I am sorry ,i'm still don't know how to use new{} to get other I want and access the fields by name
Then you just do exactly like you do in your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.