I've got a generic<> function that takes a linq query ('items') and enumerates through it adding additional properties. How can I select all the properties of the original 'item' rather than the item itself (as the code below does)?
So equivalent to the sql: select *, 'bar' as Foo from items
foreach (var item in items)
{
var newItem = new {
item, // I'd like just the properties here, not the 'item' object!
Foo = "bar"
};
newItems.Add(newItem);
}
LINQ queries are based on generic types, which were introduced in version 2.0 of . NET Framework. You do not need an in-depth knowledge of generics before you can start writing queries.
All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!
Select method is used to select one or more items from collection or list object, here we see some example of linq select statement. variableName. Select(s => s.Name); There are various ways we can select some records or single record from a collection object.
There's no easy way of doing what you're suggesting, as all types in C# are strong-typed, even the anonymous ones like you're using. However it's not impossible to pull it off. To do it you would have to utilize reflection and emit your own assembly in memory, adding a new module and type that contains the specific properties you want. It's possible to obtain a list of properties from your anonymous item using:
foreach(PropertyInfo info in item.GetType().GetProperties())
Console.WriteLine("{0} = {1}", info.Name, info.GetValue(item, null));
Shoot you wrote exactly what i was going to post. I was just getting some code ready :/
Its a little convoluted but anyways:
ClientCollection coll = new ClientCollection();
var results = coll.Select(c =>
{
Dictionary<string, object> objlist = new Dictionary<string, object>();
foreach (PropertyInfo pi in c.GetType().GetProperties())
{
objlist.Add(pi.Name, pi.GetValue(c, null));
}
return new { someproperty = 1, propertyValues = objlist };
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With