Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq equivalent of 'select *' sql for generic function?

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);
}
like image 982
Nick Avatar asked Sep 21 '08 01:09

Nick


People also ask

Is LINQ generic?

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.

Can I use LINQ query for a type derived from IEnumerable?

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!

How do I write a selection in LINQ?

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.


2 Answers

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));
like image 183
Kris Avatar answered Sep 30 '22 18:09

Kris


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 };
});
like image 31
mattlant Avatar answered Sep 30 '22 19:09

mattlant