0

I am trying to grab unique values from a DataTable Column into a list. The table & column name (plus potentially type) will vary with each usage of the function. How do I change the data type for the group by line using variables (or other).

    private IEnumerable<string> GetSeparateParent(DataColumn parentAlpha)
    {
        DataTable dt = parentAlpha.Table;
        string fieldName = parentAlpha.ColumnName;
        IEnumerable<string> parent;
        Type ColumnType = parentAlpha.DataType;

        parent = from a in dt.AsEnumerable()
                 group a by a.Field<ColumnType>(parentAlpha) into g
                 select new
                 {
                     Alpha = g.Key.ToString()
                 };

        return parent;
    }

ANy suggestions?

GPS
  • 1
  • 2
  • 2
    Possible duplicate of [C# use System.Type as Generic parameter](https://stackoverflow.com/questions/4667981/c-sharp-use-system-type-as-generic-parameter) – GSerg May 10 '20 at 10:02
  • Possibly not also. The question was more related to how do I use this knowledge in the group by line (line 6), which requires me to provide the type of the field in the group by clause. I used reflecion in line 4 to obtain the Type of the field in question however, the use of this type in line 6 is obviously incorrect. – GPS May 10 '20 at 11:36
  • You did not use reflection on line 4, you simply accessed the [`DataColumn.DataType` property](https://docs.microsoft.com/en-us/dotnet/api/system.data.datacolumn.datatype?view=netcore-3.1#System_Data_DataColumn_DataType). The referenced question shows exactly how to construct the type of call you want via reflection. The only quirk is that [`.Field`](https://docs.microsoft.com/en-us/dotnet/api/system.data.datarowextensions.field?#System_Data_DataRowExtensions_Field__1_System_Data_DataRow_System_Data_DataColumn_) is an extension method so see https://stackoverflow.com/q/1452261/11683. – GSerg May 10 '20 at 12:27
  • It's also not clear [why](https://meta.stackexchange.com/q/66377/147640) you wanted the `Field` version if the first place. You are converting everything to strings, and the only reason you are using `group` is to eliminate duplicates, that would be `parent = dt.AsEnumerable().Select(r => r[parentAlpha].ToString()).Distinct()`. – GSerg May 10 '20 at 12:32
  • Thankyou GSerg. Your first comment left me concerned that you had answered a different question & then closed my post so that noone else could provide a proper answer. Your second comment will probably answer my question, but your 3rd comment was a gem & I now have a much better solution. Tankyou. – GPS May 11 '20 at 12:39

0 Answers0