stardotstar
stardotstar

Reputation: 318

Disitinct Dynamic Linq

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

Upvotes: 0

Views: 838

Answers (1)

Alex Hodge
Alex Hodge

Reputation: 76

You could do this with reflection

var results = gridData.Select(r => r.GetType().GetProperty(colName).GetValue(r)).Distinct();

Upvotes: 1

Related Questions