Reputation: 1074
I get an Array of strings that has names of properties in it. I want to only load these properties when getting data, in this case from a DB trough Entity Framework. Something like:
var result = db.myTable
.Where(x => x.Id == ”someValue”)
.Select(y => new {y.someProperty, y.someOtherproperty, ...});
How do I create the Anonymous object from the string array. I would like to have something like:
var MyObj = new {};
foreach(var I in MyStrinArr)
{
... Add the properties here ...
}
var result = db.myTable.Where(x => x.Id==”someValue”).Select(y => obj);
Upvotes: 6
Views: 769
Reputation: 221
solution with IQueryable.Select extensions (github):
using LinqString; // nuget
var result = db.myTable
.Where(x => x.Id == "someValue")
.Select("someProperty", "someOtherProperty")
.ToList();
Upvotes: 0
Reputation: 22083
That's not (directly) possible, because anonymous classes are generated at compile-time. Iterating over a string array is at runtime. So this isn't comparable.
There are possibilities with dynamic linq, you should read the ScottGu's Blog
on this: dynamic-linq It is using techniques creating types with properties at runtime. Download the dynamiclinqcsharp file and check the source. There is a ClassFactory
within the DynamicLibrary.cs, which allows you to create types. public Type GetDynamicClass(IEnumerable<DynamicProperty> properties)
Upvotes: 3