Reputation: 5083
I have not used LINQ before and have need to do dynamic queries on a dynamically built datatable. I am investigating different options and want to know if LINQ can mimic this SQL query example when run on an untyped datatable. The datatable's structure is dynamic according to what source and fields a user selects.
Can LINQ do this:
select CAST(EventID as varchar(8)) + '_' + CAST(UserID as varchar(8)) as UserEventRef
from tblEvent
I have to allow the user to build their own query and allow them to do calculations and casts as they wish.
EDIT: The result must NOT be strongly typed.
Upvotes: 0
Views: 2462
Reputation: 1840
I am assuming the purpose is to have a strongly typed result to work with. You can select whatever columns you want and cast or convert them to whatever types you want, but I am not sure how you are going to create your dynamic user defined types.
This code will do what you showed above:
from e in tblEvent
select new
{
UserEventRef = String.Format("{0}_{1}", EventId.ToString(), UserId.ToString())
}
This will create an anonymous type, but it is still defined at design time, not run time.
Upvotes: 0
Reputation: 31723
This should work. It is a client side transformation. That means the EventId and UserId are both queried from the db and a new anonymous class is created with the computed property Summary
var result = from e in Event
select new {
e.EventId,
e.UserId,
Summary = e.EventId.ToString("00000000") + "_" + e.UserID.ToString("00000000")
};
Upvotes: 0
Reputation: 11477
Sure.
from t in tblEvent
select new { UserEventRef = EventID.ToString() + "_" + UserID.ToString() }
Upvotes: 1
Reputation: 44776
It can certainly cast, yes. It won't be very useful for dynamic queries on a dynamic datatable, however, since you have no C# types to code against.
Upvotes: 0