答案 0 :(得分:1)
我认为您可以使用System.Data.DataView的ToTable(distinct,columns)方法。以下是代码示例:
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Col1", "Col2" ,"Col3","Col4","Col5");
答案 1 :(得分:1)
// DataTable dt = new DataTable(); for (int i = 1; i < 6; i++) dt.Columns.Add("Col" + i);
// foreach (var c in "EEFG") dt.Rows.Add(("A B C D " + c).Split()); // optional to generate the table
dt = dt.Rows.Cast<DataRow>()
.GroupBy(r => Tuple.Create(r[0], r[1], r[2], r[3])) // group by the first 4 values in each row (you can replace the numbers with the indexes or names of your columns)
.SelectMany(g => g.GroupBy(r => r[4], (k, v) => v.First())) // group each group by the 5th value, and select the first row in each group, to get the distinct rows
.CopyToDataTable(); // optional to copy the rows to a new DataTable
Debug.Print(string.Join("\n", dt.AsEnumerable().Select(r => string.Join("\t", r.ItemArray)))); // optional to print the result
如果没有其他列,可以缩短它以获取每个组中的不同行:
dt = dt.Rows.Cast<DataRow>().GroupBy(r => Tuple.Create(r[0], r[1], r[2], r[3]))
.SelectMany(g => g.Distinct(DataRowComparer.Default)).CopyToDataTable();
答案 2 :(得分:-1)
运行此选项并查看k
和dr
值
var groups = dt.AsEnumerable().GroupBy(x => new { col1 = x["col1"], col2 = x["col2"], col3 = x["col3"], col4 = x["col4"] });
foreach (var group in groups)
{
var k = group.Key;
foreach (var dr in group)
{
}
}
答案 3 :(得分:-2)
我的猜测与c#一样,数据表最有效的方法是使用Linq:
var consolidatedChildren =
from c in children
group c by new
{
c.Col1,
c.Col2,
c.Col3,
c.Col4
} into gcs
select new ConsolidatedChild()
{
Col1= gcs.Key.Col1,
Col2= gcs.Key.Col2,
Col3= gcs.Key.Col3,
Col4= gcs.Key.Col4,
Col5= gcs.ToList(),
};
虽然我并非100%确定这会返回Col5,但应该有办法使用Linq来做到这一点。
编辑:使用儿童应该更容易/更清洁。