Disitinct Dynamic Linq

c# dynamic-linq linq

Question

I need an IEnumerable in order to retrieve Distinct values.

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

As needed by System.Linq.Dynamic, I must utilize an IQueryable to determine the column name at run time.

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

I reasoned that I should load a List of Strings into a JsonResult as I want my function to produce JSON. However, I'm having trouble obtaining a column with both discrete values and run-time flexibility.

So I suppose my query is, "How do I accomplish this with LINQ?"

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

1. Update

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

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

That gives me a "Type 'System.Linq.IQueryable' cannot be automatically converted to 'System.Collections.Generic.List'. There is an explicit conversion (do you need a cast?)"

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

Accepted Answer

You might do this by reflecting.

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