我有这样的DataTable:
|inflation|budget |reserve
1|decrease |no_change|increase
2|decrease |increase |decrease
3|no_change|increase |increase
4|no_change|increase |decrease
5|no_change|no_change|decrease
6|no_change|increase |no_change
7|decrease |increase |increase
8|no_change|no_change|increase
和行号列表:1, 2, 4, 5, 7
。
我想获得包含在行号列表中的所有不同值。结果应如下所示:
inflation-decrease { 1, 2, 7 }
inflation-no_change { 3, 4, 5, 6, 8 }
budget-no_change { 1, 5, 8 }
budget-increase { 2, 3, 4, 6, 7 }
reserve-increase { 1, 3, 7, 8 }
reserve-decrease { 2, 4, 5 }
有更好的方法来实现使用Linq而不是循环遍历列,然后循环遍历行?数据可能会发生变化,因此我不能依赖列名。
修改 我对这个问题的解决方案是:
public class Rule
{
public String atribute { get; set; }
public String value { get; set; }
public Rule() { }
public Rule(String atribute, String value)
{
this.atribute = atribute;
this.value = value;
}
public override string ToString()
{
return atribute + "-" + value;
}
}
public class RuleObject
{
public Rule rule { get; set; }
public List<int> indexList { get; set; }
public RuleObject() { }
public RuleObject(Rule rule, List<int> indexList)
{
this.rule = rule;
this.indexList = indexList;
}
public override string ToString()
{
return rule.ToString() + " { " + string.Join(",", indexList.ToArray()) + " }";
}
}
public static class Program
{
public static void Main()
{
DataTable dataTable = new DataTable();
dataTable.Columns.Add("inflation");
dataTable.Columns.Add("budget");
dataTable.Columns.Add("reserve");
dataTable.Rows.Add("", "", ""); //dirty solution to start count row number from 1
dataTable.Rows.Add("decrease", "no_change", "increase");
dataTable.Rows.Add("decrease", "increase", "decrease");
dataTable.Rows.Add("no_change", "increase", "increase");
dataTable.Rows.Add("no_change", "increase", "decrease");
dataTable.Rows.Add("no_change", "no_change", "decrease");
dataTable.Rows.Add("no_change", "increase", "no_change");
dataTable.Rows.Add("decrease", "increase", "increase");
dataTable.Rows.Add("no_change", "no_change", "increase");
List<int> rowNumbersList = new List<int>() { 1, 2, 4, 5, 7 };
foreach (DataColumn dataColumn in dataTable.Columns)
{
var distinct = (from row in dataTable.AsEnumerable()
select new
{
atribute = dataColumn.ColumnName,
value = row.Field<string>(dataColumn.ColumnName),
index = dataTable.Rows.IndexOf(row)
}
).GroupBy(x => x.value)
.Select(g => new RuleObject()
{
rule = new Rule(g.Select(h => h.atribute).First(), g.Key),
indexList = g.Select(h => h.index).ToList()
}
).Where(x => rowNumbersList.Intersect(x.indexList).Any());
foreach (var d in distinct)
{
Console.WriteLine(d.ToString());
}
}
}
}
您对此解决方案有何看法?