dynamic string C# .ToTable(true, "Dynamic String Here");

1.1k Views Asked by At

I am building a table on the fly in C#. This table may or may not contain certain columns. I need a row made up of the distinct values from a raw table. (i.e. Agent Name, Manager Name etc).

I use:

var DistinctTable = SourceTable.DefaultView.ToTable(true, "AName", "MName");

and it works fine, but I need this to work with something like

    string Groupby = "";

    if (AName != "")
    {
        Groupby = AName;
    }
    if (MName != "")
    {
        Groupby = Groupby + MName;
    }

var DistinctTable = SourceTable.DefaultView.ToTable(true, Groupby);

I'm dumbing this down a bit for simplicity but the premise is there. I have tried options of adding in quotes, adding in comma's etc. Nothing works the best I have done is to receive the error

There is no column '"AName","MName"' in table (x)

is this possible?

2

There are 2 best solutions below

3
Hugo Yates On

As DistinctTable is being made (back?) into a DataTable you can therefore do this:

if (DistinctTable.Columns.Contains("ColumnName"))
{
    //[logic]
}

Edited to add:

DataTable DistinctTable = SourceTable.DefaultView.ToTable();
if (DistinctTable.Rows.Count > 0)
{
    if (!DistinctTable.Columns.Contains("ColumnA"))
    {
        DistinctTable.Columns.Add("ColumnA", typeof(String));
    }
    if (!DistinctTable.Columns.Contains("ColumnB"))
    {
        DistinctTable.Columns.Add("ColumnA", typeof(String));
    }
    if (!DistinctTable.Columns.Contains("ColumnC"))
    {
        DistinctTable.Columns.Add("ColumnC", typeof(String));
        //you can also move the new columns by using SetOrdinal, like so:
        DistinctTable.Columns[DistinctTable.Columns.Count - 1].SetOrdinal(DistinctTable.Columns.Count - 2);
        //but careful, this gets messy very quickly
    }
}
//return DistinctTable //(?)
2
juharr On

The second parameter of DefaultView.ToTable is params string[] so you should be able to create an array to pass into it.

List<string> groupBys = new List<string>();

if (AName != "")
{
    groupBys.Add(AName);
}
if (MName != "")
{
    groupBys.Add(MName);
}

var DistinctTable = SourceTable.DefaultView.ToTable(true, groupBys.ToArray());