How can I do a distinct on a dynamically selected column?

dynamic-linq linq

Question

I am using dynamic linq and selecting a column dynamically. I need to do a distinct on this. How could I do this?

var qry = tbl.AsEnumerable().AsQueryable()
             .Select("new(it[\"" + this.UniqueName + "\"]
             .ToString() as " + this.UniqueName + ")");

Thanks.

1
3
7/13/2012 3:26:20 PM

Popular Answer

Instead of using

as " + this.UniqueName + "

do

as someFixedColumnName

and run your Distinct() clause on that, using ordinary Linq.


Alternatively, you could try this extension method:

public static IQueryable DynamicDistinct(this IQueryable source)
{
    if (source == null) throw new ArgumentNullException("source");
    return source.Provider.CreateQuery(
        Expression.Call(
            typeof(Queryable), "Distinct",
            new Type[] { source.ElementType },
            source.Expression));
}
4
4/14/2011 7:46:23 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow