我有一個數據表像上面的,什麼是過濾行
的有效途徑- Col1中,col2的,COL3,COL4應與其它行匹配(一個或多個)
- COL5不同
類似下面,
如何提取其中由COL5
感謝
我有一個數據表像上面的,什麼是過濾行
的有效途徑類似下面,
如何提取其中由COL5
感謝
我認爲你可以使用ToTable System.Data.DataView的(不同,列)方法。下面是代碼示例:
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Col1", "Col2" ,"Col3","Col4","Col5");
我的猜測是一如既往地與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。
編輯:使用兒童應該更容易/更清潔。
運行此,看到了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)
{
}
}
// 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();
來過濾他們的DataGridView?你的意思是刪除前4列的重複? – Slai
@Slai我想提取其中4個值相匹配的數據行和第五列的值而變化 – karthik