Disitinct Dynamic Linq

c# dynamic-linq linq

Question

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?)"

1
0
11/21/2016 1:03:10 AM

Accepted Answer

You could do this with reflection

var results = gridData.Select(r => r.GetType().GetProperty(colName).GetValue(r)).Distinct();
1
11/21/2016 12:59:19 AM


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