如何循环使用DataTable并在条件下使用逗号分隔符连接列值

时间:2014-01-14 10:41:00

标签: c# .net

  ViewID   FilterType     filtervalue
    1        COMPANY        ONS 
    1        COMPANY        TEK 
    1        CUSTOMERID     178822 
    1        MANAGERID      05082807 
    1        SITEID         00525 
    1        SITEID         00720 

如果filtervalue中的值与以逗号分隔的值相同,我需要加入FilterType column列的值company in('ONS','TEK')

3 个答案:

答案 0 :(得分:1)

只需按FilterType列值对其进行分组,然后(对于每个组)选择filtervalue列值并提取不同的值:

var groupColumn = table.Columns["FilterType"];
var valueColumn = table.Columns["filtervalue"];

foreach (var group in table.Rows.Cast<DataRow>().GroupBy(x => x[groupColumn]))
{
    var values = group
        .Select(x => String.Format("'{0}'", x[valueColumn]))
        .Distinct();

    // This is value you need for one group (by FilterType)    
    string text = String.Format("{0} IN ({1})",
        group.Key, String.Join(",", values));
}

对于您的示例中的数据,如果您将text打印到控制台,您将获得:

COMPANY IN ('ONS','TEK')
CUSTOMERID IN ('178822') 
MANAGERID  IN ('05082807')
SITEID IN ('00525', '00720')

答案 1 :(得分:0)

public string getFiltervalue(string filterType, DataTable dt)
{
    HashSet<string> values = new HashSet<string>();
    foreach(DataRow row in dt.Rows)
    {
         if(row["FilterType"].ToString().Equals(filterType))
         {
             values.Add("'" + row["FilterType"].ToString() + "'");
         }
    }

    String[] array = new String[values.Count];
    values.CopyTo(array);

    return filterType + " in (" + String.Join(",", array) + ")";
}

答案 2 :(得分:0)

使用LINQ,显而易见的是,您必须按FilterType对查询结果进行分组,然后使用简单的Select进行分组,您可以获得所需的方式。但是逗号分隔FilterValue有点棘手但可以通过string.join()轻松实现。以下是包含示例数据的查询:

List<Record> records = new List<Record>() 
{
    new Record() { ViewId = 1, FilterType = "COMPANY", FilterValue = "ONS" },
    new Record() { ViewId = 1, FilterType = "COMPANY", FilterValue = "TEK"}, 
    new Record() { ViewId = 1, FilterType = "CUSTOMERID", FilterValue = "178822"}, 
    new Record() { ViewId = 1, FilterType = "MANAGERID", FilterValue = "05082807"}, 
    new Record() { ViewId = 1, FilterType = "SITEID", FilterValue = "00525" },
    new Record() { ViewId = 1, FilterType = "SITEID", FilterValue = "00720" }
};

var result = records.GroupBy(rec => rec.FilterType)
                    .Select(g =>
                                new
                                {
                                    g.Key,
                                    Values = string.Join(",", g.Select(r => r.FilterValue).ToArray())
                                });