0

To get Distinct values, I need an IEnumerable.

var results = gridData.Select(r => r.ExplicitColumnName).Distinct();

To decide the column name at run time, I need to use an IQueryable as required by System.Linq.Dynamic.

var results = gridData.AsQueryable().Select(columnNameIsInThisVar);

I want my method to return json so figured List of string and then load that into a JsonResult. But I'm having problems getting both distinct values and run-time flexibility on column.

So I guess my question is, in LINQ, how do I do this?

List<string> results = $"select distinct {columnName} from ridiculous_table_with_100_columns";

Update 1

As per comments, I've now installed dynamic Linq as a nuget package but I still can't convert to List.

filterValues = gridData.AsQueryable().Select(columnName).Distinct();

Which gets me a "Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)"

stardotstar
  • 318
  • 2
  • 18
  • By adding `Distinct` at the end (after `Select`)? Dynamic LINQ defines `Distinct` on `IQueryable`. – Ivan Stoev Nov 21 '16 at 00:39
  • Dynamic Linq doesn't provide a Distinct method. After the select, an IQueryable is returned. It needs to be converted to IEnumerable but I can't think of a way to do that without building it manually by iterating over the IQueryable, in which case I might just as well filter out the duplicates myself. – stardotstar Nov 21 '16 at 00:41
  • I see `public static IQueryable Distinct(this IQueryable source);` inside `System.Linq.Dynamic.DynamicQueryable`. – Ivan Stoev Nov 21 '16 at 00:44
  • 1
    Aaah. I got my Dynamic.cs from the CSharpSamples zip as it was linked from an old blog entry from ScottGu. A quick google revealed it's now available as a nuget package and this one _does_ have the Distinct method. My bad. Thanks for the nudge :-) – stardotstar Nov 21 '16 at 00:54
  • You are welcome, glad it helped :) – Ivan Stoev Nov 21 '16 at 01:01
  • The return value from `Distinct()` is another `IQueryable`, you need to evaluate the LINQ statements. Call `.ToList()` after `Distinct()`, this will evaluate the expression tree into a `List`. – Xenolightning Nov 21 '16 at 01:38

1 Answers1

1

You could do this with reflection

var results = gridData.Select(r => r.GetType().GetProperty(colName).GetValue(r)).Distinct();
Alex Hodge
  • 76
  • 4